Shiro 101

Hello World Example

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>biz.tugay</groupId>
    <artifactId>shiro-pg</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.2</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
</project>

InMemoryRealm.java

package biz.tugay.shiropg;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.*;

public class InMemoryRealm extends AuthorizingRealm {

    private Map<String, String> credentials = new HashMap<>();

    {
        credentials.put("koraytugay", "password");
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken aToken)
            throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) aToken;
        String username = token.getUsername();
        return new SimpleAuthenticationInfo(username, credentials.get(username), getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}

Main.java

package biz.tugay.shiropg;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

class Main {

    static {
        SecurityUtils.setSecurityManager(new DefaultSecurityManager(new InMemoryRealm()));
    }

    public static void main(String[] args) {
        UsernamePasswordToken token = new UsernamePasswordToken("koraytugay", "password");

        Subject subject = SecurityUtils.getSubject();
        subject.login(token);

        if (subject.isAuthenticated())
            System.out.println("Hello " + subject.getPrincipal());
    }
}