Multi-Realm and Jdbcrealm configuration

Source: Internet
Author: User

Multi-Realm configuration

public class MYREALM1 implements Realm {public String getName () {return ' myrealm1 '; } public Boolean supports (Authenticationtoken token) {return token instanceof Usernamepasswordtoken;//Support Usern only Amepasswordtoken type token} public authenticationinfo Getauthenticationinfo (Authenticationtoken token) throws Authent  icationexception {String username = (string) token.getprincipal (); Get user name string password = new string ((char[]) token.getcredentials ()); Get the password if (!) Zhang ". Equals (username)) {throw new unknownaccountexception ();//If the user name is wrong} if (!") 123 ". Equals (password)) {throw new incorrectcredentialsexception ();//If the password is wrong}//If authentication authentication is successful, return a    Uthenticationinfo implementation; return new Simpleauthenticationinfo (username, password, getName ());    }}public class MYREALM2 implements Realm {public String getName () {return ' myrealm2 '; } public Boolean supports (Authenticationtoken token) {       return token instanceof Usernamepasswordtoken; Only token of Usernamepasswordtoken type is supported AuthenticationInfo Getauthenticationinfo (Authenticationtoken token) thro  WS Authenticationexception {string username = (string) token.getprincipal (); Get user name string password = new string ((char[]) token.getcredentials ()); Get the password if (!) Wang ". Equals (username)) {throw new unknownaccountexception ();//If the user name is wrong} if (!" 123 ". Equals (password)) {throw new incorrectcredentialsexception ();//If the password is wrong}//If authentication authentication is successful, return a    Uthenticationinfo implementation; return new Simpleauthenticationinfo (username, password, getName ()); }}[main] #声明一个realmmyRealm1 =com.github.zhangkaitao.shiro.chapter2.realm.myrealm1myrealm2= com.github.zhangkaitao.shiro.chapter2.realm.myrealm2# Specifies the realms implementation of the SecurityManager securitymanager.realms=$ MYREALM1, $myRealm 2

The

Securitymanege is authenticated in the order specified by realm, and is not specified (SECURITYMANAGER.REALMS=MYREALM1,MYREALM2), which is used in the order of Declaration. When the specified realm is displayed, other realms that are not specified will be ignored, such as: securitymanage.realms= $myRealm 1, then MYREALM2 will not be set into realms.

@Test    public void testCustomMultiRealm() {        //1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager        Factory<org.apache.shiro.mgt.SecurityManager> factory =                new IniSecurityManagerFactory("classpath:shiro-multi-realm.ini");        //2、得到SecurityManager实例 并绑定给SecurityUtils        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();        SecurityUtils.setSecurityManager(securityManager);        //3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)        Subject subject = SecurityUtils.getSubject();        UsernamePasswordToken token = new UsernamePasswordToken("wang", "123");        try {            //4、登录,即身份验证            subject.login(token);        } catch (AuthenticationException e) {            //5、身份验证失败            e.printStackTrace();        }        Assert.assertEquals(true, subject.isAuthenticated()); //断言用户已经登录        //6、退出        subject.logout();    }

Jdbcrealm use

[main]jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealmdataSource=com.alibaba.druid.pool.DruidDataSourcedataSource.driverClassName=com.mysql.jdbc.DriverdataSource.url=jdbc:mysql://localhost:3306/shirodataSource.username=rootdataSource.password=rootjdbcRealm.dataSource=$dataSourcesecurityManager.realms=$jdbcRealm

Test code Ibid.

Issue record:

How do I set the content to be placed in token when I log in using credentials and then get token information?

View Jdbcrealm class source code, you can see Dogetauthenticationinfo (Authenticationtoken Token) method returns a Simpleauthenticationinfo info= new Simpleauthenticationinfo (username, Password.tochararray (), This.getname ()), so only username was placed in token.

The following custom realm class, which queries the database internally, synthesizes custom Realms and Jdbcrealm.

public class Samplerealm extends Authorizingrealm {@Autowired uuserservice userservice;    @Autowired Permissionservice Permissionservice;    @Autowired RoleService RoleService;    Public Samplerealm () {super (); }/** * Authentication information, mainly for user login, */protected AuthenticationInfo Dogetauthenticationinfo (Authenticationtok        En authctoken) throws authenticationexception {Shirotoken token = (shirotoken) Authctoken;        Uuser user = Userservice.login (token.getusername (), token.getpswd ()); if (null = = user) {throw new Accountexception ("The account number or password is incorrect!            "); /** * If the user's status is disabled.  Then throw <code>DisabledAccountException</code> */} else if (Uuser._0.equals (User.getstatus ())) {throw new Disabledaccountexception ("account has been banned from login!)        ");            } else {//update login time last login user.setlastlogintime (new Date ());   Userservice.updatebyprimarykeyselective (user);     } return new Simpleauthenticationinfo (user, user.getpswd (), GetName ()); }/** * Authorized */@Override protected authorizationinfo dogetauthorizationinfo (principalcollection principals        {Long userId = Tokenmanager.getuserid ();        Simpleauthorizationinfo info = new Simpleauthorizationinfo ();        Based on the User ID query roles (role), put into authorization.        set<string> roles = Roleservice.findrolebyuserid (userId);        Info.setroles (roles);        Based on the User ID query permission (permission), put into the authorization.        set<string> permissions = Permissionservice.findpermissionbyuserid (userId);        Info.setstringpermissions (permissions);    return info; /** * Empty Current user rights information */public void Clearcachedauthorizationinfo () {principalcollection Principalcolle        ction = Securityutils.getsubject (). Getprincipals ();        simpleprincipalcollection principals = new Simpleprincipalcollection (PrincipalCollection, GetName ()); Super.cleaRcachedauthorizationinfo (principals); }/** * Specifies principalcollection clear */public void Clearcachedauthorizationinfo (PrincipalCollection Principalco llection) {simpleprincipalcollection principals = new Simpleprincipalcollection (principalcollectio        N, GetName ());    Super.clearcachedauthorizationinfo (principals); }}

Key point: The return value of the Dogetauthenticationinfo (Authenticationtoken token) method

return new Simpleauthenticationinfo (user, user.getpswd (), GetName ()), so the token returned is a user entity.

Multi-Realm and Jdbcrealm configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.