This article is from netease Cloud community

Author: Wang Fei


The above configuration can be used after walking, the following personal needs, and stepped on the pit:

1, How to change the name of cookies, the default name “rememberMe” is too ugly

First throw a paper, about change the cookie: blog.csdn.net/lhacker/art…

Shiro’s SimpleCookie provides two methods for modifying cookie names:

The first is to change the name of the cookie directly through the constructor method, as shown in shiro’s configuration file:

1 <constructor-arg value=”COOKIE_NAME” />

The SimpleCookie method is called:

1 public SimpleCookie(String name) { 2 this(); 3 this.name = name; 4}Copy the code
SimpleCookie also provides other constructors to use, as shown in the source code.Copy the code

The second method is to assign the name field of SimpleCookie as I did in the link:

1 <property name=”name” value=”COOKIE_NAME” />

Other SimpleCookie fields can be configured as follows:

1 private String name; 2 private String value; 3 private String comment; 4 private String domain; 5 private String path; 6 private int maxAge; 7 private int version; 8 private boolean secure; 9 private boolean httpOnly;Copy the code

2. Why not call doGetAuthorizationInfo to get the authorization information?

Annotations to take effect need to be configured in servlet.xml as follows:

      <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager" />
    </bean>Copy the code

3. An interface can be called by different pages with different permissions.

When we use permission annotations, we often run into the problem that the interface can be reused, but the permissions need to be separated.

First take a look at the source code for the @Requirespermissions annotation:

  1 @Target({ElementType.TYPE, ElementType.METHOD})
 2 @Retention(RetentionPolicy.RUNTIME)
 3 public @interface RequiresPermissions {
 4 
 5     /**
 6      * The permission string which will be passed to {@link org.apache.shiro.subject.Subject#isPermitted(String)}
 7      * to determine if the user is allowed to invoke the code protected by this annotation.
 8      */
 9     String[] value();
10     
11     /**
12      * The logical operation for the permission checks in caseMultiple roles are specified. AND is the default 13 * @since 1.1.0 14 */ 15 Logical Logical () default Logical. 16 17}Copy the code

The key of the annotation is stored in the value array. In addition, there is a Logical value for the relationship between multiple permissions, so when we need to satisfy multiple permissions in a method, we can do this:

@RequiresPermissions(value = { "key1"."key2" }, logical = Logical.AND)Copy the code

This can be done when a method satisfies any permission key

@RequiresPermissions(value = { "key1"."key2" }, logical = Logical.OR)Copy the code

4. How to use a non-user password to log in?

Encountered this problem, my solution is to deal with the authentication mode in advance, and then call the subject login, the general process is as follows:

// Handle login logic verification mobile phone verification code...... // Subject login UsernamePasswordToken token = new UsernamePasswordToken(email,"openid".true); // username field can put the id/ account/mobile phone number/email and other unique values // password store a current account must carry a message, if there is a password in the authentication process can store the password, can directly store any string, this does not matter, here is a string character"openid"
SecurityUtils.getSubject().login(token);Copy the code

The subject login method indirectly calls the doGetAuthenticationInfo method to obtain the authentication information. The source code of a method is given above

 1 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
 2         try {
 3             UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
 4             String email = token.getUsername();
 5             String password = new String(token.getPassword());
 6             if(! StringUtils.isEmpty(email) &&"openid".equals(password)) {7 // if username is not null and password is the given string 8 // If username is null and password is the given string 8 // If username is null and password is not the given string 9 // If username is not null and password is not the given string You can also pull the entire user information out of the database and put it in the Principal field of SimpleAuthenticationInfo 10return new SimpleAuthenticationInfo("Content you want to cookie"."openid", getName());
11             }
12             logger.info("Login authentication failed, Shiro does not add permission information");
13             return null;
14         } catch (Exception e) {
15             logger.error(Shiro authentication exception:, e);
16             returnnull; 18 17}}Copy the code

5. Data stored in cookies cannot be serialized?

The principal field in SimpleAuthenticationInfo is Serializable, and Serializable is not implemented by the model. The principal field in SimpleAuthenticationInfo is Serializable.

1 public class User implements Serializable{ 2 ...... 3}Copy the code

6. What do configurations and annotations do in shro.xml?

Annotations and the filter configured in Shro.xml are two sets of permission validation processes provided by Shiro, and they are called differently

This document to filter the relevant comments wrong comparatively detailed introduction: blog.csdn.net/clj19860606…

Here’s an excerpt from the ShiroFilterFactoryBean configuration in Shiro.xml:

SecurityManager: This property is required.

LoginUrl: Automatically redirects to the login page when an unlogged user requests a page to be logged in to. This attribute is not required. If you do not enter an address, the system automatically searches for the “/login.jsp” page in the root directory of the project Web project.

SuccessUrl: The page is displayed by default if the login is successful. If the page is not configured, the page is displayed as /. If you click a page that needs to be logged in before login, you will automatically jump to the page that needs to be logged in. Do not jump to this.

UnauthorizedUrl: a page that does not have permission to jump to by default.

Filter abbreviation

Corresponding Java class

anon

org.apache.shiro.web.filter.authc.AnonymousFilter

authc

org.apache.shiro.web.filter.authc.FormAuthenticationFilter

authcBasic

org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter

perms

org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter

port

org.apache.shiro.web.filter.authz.PortFilter

rest

org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter

roles

org.apache.shiro.web.filter.authz.RolesAuthorizationFilter

ssl

org.apache.shiro.web.filter.authz.SslFilter

user

org.apache.shiro.web.filter.authc.UserFilter

logout

org.apache.shiro.web.filter.authc.LogoutFilter

Anon: example /admins/**= Anon has no parameter and can be used anonymously.

Authc: For example, /admins/user/**=authc indicates that authentication is required

Roles: For example, admins/user/**=roles[admin], multiple parameters can be quoted and separated by commas. For example, admins/user/**=roles[“admin,guest”], each parameter is passed. Equivalent to the hasAllRoles() method.

Perms: For example, /admins/user/**=perms[user:add:*], multiple parameters can be quoted and separated by commas. For example, /admins/user/**=perms[“user:add:*,user:modify:*”], When there are multiple arguments, each argument must be passed, like the isPermitedAll() method.

Rest: example /admins/user/**=rest[user], according to the request method, equivalent to /admins/user/**=perms[user:method], method is POST, get, delete, etc.

Port: example/admins/user / * * = port [8081], when the request is the url of the port is not 8081 jump to schemal: / / serverName: 8081? QueryString, where schmal is the protocol HTTP or HTTPS, serverName is the host you’re accessing,8081 is the port of port in the URL configuration, queryString

Is it from the URL you visited? The following parameters.

AuthcBasic: For example, /admins/user/**=authcBasic No parameter indicates httpBasic authentication

SSL: example /admins/user/**= SSL Indicates a secure URL request using HTTPS

User: for example, /admins/user/**=user If no parameter is specified, the user must exist. No check is performed during login

Note: Anon, authcBasic, auCHc, user are authentication filters,

Perms, ROLES, SSL, REST, and Port are authorization filters


The permission information in annotations is realized by obtaining authorization information:

@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        try {
            Iterator<String> iter = principals.fromRealm(getName()).iterator();
            if(! iter.hasNext()) { logger.info("Shiro authentication has no permission");
                return null;
            }
            String email = iter.next();
            if(! Strings. IsNullOrEmpty (email)) {// Access permission information can be obtained in real time through email, of course, iter itself has permission information, no database or redis query //set auth
                SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
                info.addStringPermissions(new ArrayList<String>("Permission set"));
                return info;
            }
            logger.info("Mailbox is empty");
            return null;
        } catch (Exception e) {
            logger.error("Shiro permission obtaining exception :", e);
            returnnull; }}Copy the code

Conclusion:

It is the first time to use Shiro for permission verification. I feel that Shiro’s permission verification is more flexible and easy to understand, and more suitable for novice access, and the control of permission is also relatively simple. The questions mentioned above are the problems I have encountered during the project, and they are only personal solutions. If there are more suitable solutions, please kindly point out, thank you very much.


Netease Cloud Free experience pavilion, 0 cost experience 20+ cloud products!

For more information about NETEASE’s r&d, product and operation experience, please visit netease Cloud Community.


Relevant article: “recommended” Question | the verification code you have encountered problems might all be here step by step teach you learn to recommend 】 【 browserify