Vállalati Információs Rendszerek

Java authentication frameworks

Apache Shiro

Feladatok:

  • Nézzük át az apache-shiro példakódot
    • Parancssori példa
    • Felhasználó adatok ini fájlból
    • Parancssori futtatás: mvnw compile exec:java
In [5]:
>java
%%loadFromPOM
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.4.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.26</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>1.7.26</version>
</dependency>
In [1]:
>bash
vimcat shiro.ini
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================

# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

# -----------------------------------------------------------------------------
# Roles with assigned permissions
# 
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
In [4]:
>java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

Factory<SecurityManager> factory = new IniSecurityManagerFactory("shiro.ini");
SecurityManager securityManager = factory.getInstance();

SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();

Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
    System.out.println("Retrieved the correct value! [" + value + "]");
}

if (!currentUser.isAuthenticated()) {
    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
    token.setRememberMe(false);
    try {
        currentUser.login(token);
    } catch (UnknownAccountException uae) {
        System.out.println("There is no user with username of " + token.getPrincipal());
    } catch (IncorrectCredentialsException ice) {
        System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");
    } catch (LockedAccountException lae) {
        System.out.println("The account for username " + token.getPrincipal() + " is locked.  " +
                "Please contact your administrator to unlock it.");
    }
    catch (AuthenticationException ae) {
        //unexpected condition?  error?
    }
}

System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfully.");

if (currentUser.hasRole("schwartz")) {
    System.out.println("May the Schwartz be with you!");
} else {
    System.out.println("Hello, mere mortal.");
}

if (currentUser.isPermitted("lightsaber:weild")) {
    System.out.println("You may use a lightsaber ring. Use it wisely.");
} else {
    System.out.println("Sorry, lightsaber rings are for schwartz masters only.");
}

if (currentUser.isPermitted("winnebago:drive:eagle5")) {
    System.out.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
            "Here are the keys - have fun!");
} else {
    System.out.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}

currentUser.logout();
Retrieved the correct value! [aValue]
User [lonestarr] logged in successfully.
May the Schwartz be with you!
You may use a lightsaber ring. Use it wisely.
You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  Here are the keys - have fun!
  • Készítsünk egy kis alkalmazást, ami felhasználói azonosítást tartalmaz, de az adatokat ne ini fájlból vagy beégetve keresse, hanem adatbázisban tárolja, amit JDBC-vel érünk el (új Realm Shiro esetén)
In [6]:
>java
%%loadFromPOM
<dependency>
    <groupId>org.xerial</groupId>
    <artifactId>sqlite-jdbc</artifactId>
    <version>3.25.2</version>
</dependency>
In [3]:
>java
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.RolePermissionResolver;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.realm.jdbc.JdbcRealm;

public class DBRealm extends JdbcRealm {

    public DBRealm() {
        super();
        super.setRolePermissionResolver(new RolePermissionResolver() {

            @Override
            public Collection<Permission> resolvePermissionsInRole(String roleString) {
                Collection<Permission> perms = Collections.emptySet();
                try {
                    Set<String> permss = getPermissions(dataSource.getConnection(), roleString);
                    perms = new LinkedHashSet<Permission>(permss.size());
                    for (String perm : permss) {
                        perms.add(new WildcardPermission(perm));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return perms;
            }
        });

    }

    protected Set<String> getPermissions(Connection conn, String roleString) throws SQLException {
        List<String> roleNames = new ArrayList<String>();
        roleNames.add(roleString);
        return super.getPermissions(conn, "", roleNames);
    }
}
In [2]:
>bash
vimcat sqlite-users.sql
CREATE TABLE users (
  id integer PRIMARY KEY AUTOINCREMENT,
  username text NOT NULL,
  password text NOT NULL,
  password_salt text NOT NULL,
  UNIQUE (username)
);

CREATE TABLE user_roles (
  id integer PRIMARY KEY AUTOINCREMENT,
  username text NOT NULL,
  role_name text NOT NULL
);

CREATE TABLE roles_permissions (
  id integer PRIMARY KEY AUTOINCREMENT,
  permission text NOT NULL,
  role_name text NOT NULL
);
In [10]:
>bash
sqlite3 light.db "select * from users;"
echo "--------------------------------"
sqlite3 light.db "select * from user_roles;"
echo "--------------------------------"
sqlite3 light.db "select * from roles_permissions;"
1|lonestarr|$shiro1$SHA-256$500000$zyN4TT92VUW/kBHczxyT2Q==$cNANkK+vDm9HVqio/05ySVjlC5m+FLxUiGJ5F82cdUQ=|
--------------------------------
1|lonestarr|schwartz
2|lonestarr|goodguy
--------------------------------
1|lightsaber:*|schwartz
2|winnebago:drive:eagle5|goodguy
In [12]:
>java
import org.apache.shiro.authc.credential.DefaultPasswordService;

PasswordService pwdService = new DefaultPasswordService();
pwdService.encryptPassword("vespa3");
Out[12]:
$shiro1$SHA-256$500000$zyN4TT92VUW/kBHczxyT2Q==$cNANkK+vDm9HVqio/05ySVjlC5m+FLxUiGJ5F82cdUQ=
In [13]:
>java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordMatcher;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm.SaltStyle;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.sqlite.SQLiteConfig;

PasswordService pwdService = new DefaultPasswordService();
PasswordMatcher pwdMatcher = new PasswordMatcher();
pwdMatcher.setPasswordService(pwdService);
SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
DBRealm realm = new DBRealm();
org.sqlite.SQLiteDataSource ds = new org.sqlite.SQLiteDataSource(config);
ds.setUrl("jdbc:sqlite:light.db");
realm.setDataSource(ds);
realm.setCredentialsMatcher(pwdMatcher);
realm.setSaltStyle(SaltStyle.COLUMN);
SecurityManager securityManager = new DefaultSecurityManager(realm);

SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();

Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
    System.out.println("Retrieved the correct value! [" + value + "]");
}

if (!currentUser.isAuthenticated()) {
    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa3");
    token.setRememberMe(false);
    try {
        currentUser.login(token);
    } catch (UnknownAccountException uae) {
        System.out.println("There is no user with username of " + token.getPrincipal());
    } catch (IncorrectCredentialsException ice) {
        System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");
    } catch (LockedAccountException lae) {
        System.out.println("The account for username " + token.getPrincipal() + " is locked.  " +
                "Please contact your administrator to unlock it.");
    }
    catch (AuthenticationException ae) {
        //unexpected condition?  error?
    }
}

System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfully.");

if (currentUser.hasRole("schwartz")) {
    System.out.println("May the Schwartz be with you!");
} else {
    System.out.println("Hello, mere mortal.");
}

if (currentUser.isPermitted("lightsaber:weild")) {
    System.out.println("You may use a lightsaber ring. Use it wisely.");
} else {
    System.out.println("Sorry, lightsaber rings are for schwartz masters only.");
}

if (currentUser.isPermitted("winnebago:drive:eagle5")) {
    System.out.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
            "Here are the keys - have fun!");
} else {
    System.out.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}

currentUser.logout();
Retrieved the correct value! [aValue]
User [lonestarr] logged in successfully.
May the Schwartz be with you!
You may use a lightsaber ring. Use it wisely.
You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  Here are the keys - have fun!
Feladat (5 pont):
  • A jelszavakat bcrypt kódolással tároljuk el