Springsecurity for Custom token checking

Source: Internet
Author: User

Background

Spring security defaults to using "username/password" to log in, and to persist the login information by means of a cookie. In some custom scenarios, such as when you want to use the token string alone to control access to some pages, the default scenario is not supported. In the absence of the online search for relevant practices, through the official documents and individual stack overflow scattered cases, the formation of a holistic approach and practice testing through, this article is about a share of the program.

Reference

Official Document: https://docs.spring.io/spring-security/site/docs/5.0.5.BUILD-SNAPSHOT/reference/htmlsingle/

Springsecurity Verification Process

Basic springsecurity usage Online a lot, not the focus of this article, if necessary, you can search by yourself or see 54319508

The whole process of verifying is simply that the entire link has three key points,

    • The class/method/url, which requires authentication, is defined as requiring authentication (the code example in this article is a method for annotating @preauthorize ("haspermission (' TARGET ', ' PERMISSION ')")
    • Generate a visitor's permission information based on the information accessed authentication, and insert into context
    • When invoking the authentication method, verify that the permission information conforms to the permission requirement according to the specified authentication mode.

Complete call chain recommendations in the IDE through the single-step debugging experience, this article does not do related collation.

How to customize

My requirement is to use custom tokens to verify permissions that involve:

    • Generate authentication and insert into context
    • Authentication method for Token

The things to do are as follows:

    • Custom Tokenauthentication class, implement Org.springframework.security.core.Authenticaion, as token permission information
    • Custom Authenticationtokenfilter class, implements Javax.servlet.Filter, generates Tokenauthentication instances based on access information when access is received, and inserts context
    • Customizing the Securitypermissionevalutor class, implementing Org.springframework.security.access.PermissionEvaluator, and completing custom validation logic for permissions
    • In the global configuration, define the use of Securitypermissionevalutor as the permission check method
Tokenauthentication.java
/*** @author: Blaketairan */import org.springframework.security.core.Authentication;import org.springframework.security.core.GrantedAuthority;import java.util.ArrayList;import java.util.Collection;/*** Description:spring-security Custom implementation of authentication (for verifying tokens) */ Public classTokenauthenticationImplementsauthentication{PrivateString token; Public tokenauthentication(String token) { This.token= token; }@Override     Publiccollection<?extendsGrantedauthority>getauthorities() {return NewArraylist<grantedauthority> (0); }@Override     PublicObjectgetcredentials(){returnToken }@Override     PublicObjectgetdetails() {return NULL; }@Override     PublicObjectGetprincipal() {return NULL; }@Override     Public Boolean isauthenticated() {return true; }@Override     Public void setauthenticated(Booleanisauthenticated)throwsIllegalArgumentException {}@Override     PublicStringGetName() {return NULL; }}
Authenticationtokenfilter.java
/*** @author: Blaketairan */import com.google.common.base.Strings;import com.blaketairan.spring.security.configuration.TokenAuthentication;import org.springframework.context.annotation.Configuration;import org.springframework.security.core.Authentication;import Org.springframework.security.core.context.SecurityContextHolder;import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import java.io.IOException;/*** Description: Used to process received tokens and generate and inject authenticaion instances for the spring-security context */@Configuration Public classAuthenticationtokenfilterImplementsfilter{@Override     Public void Init(Filterconfig filterconfig)throwsservletexception{}@Override     Public void DoFilter(ServletRequest servletrequest, Servletresponse servletresponse,filterchain filterchain)throwsIOException, servletexception{if(ServletRequestinstanceofHttpServletRequest) {String token = ((httpservletrequest) servletrequest).GetHeader("Private-token");if(! Strings.IsNullOrEmpty(token)) {Authentication authentication =New tokenauthentication(token); Securitycontextholder.GetContext().setauthentication(authentication); System. out.println("Set Authentication with Non-empty token"); }Else{/*** When the token is not received, at least plug into the empty tokenauthenticaion instance, to avoid entering the springsecurity user name password default mode                 */Authentication authentication =New tokenauthentication(""); Securitycontextholder.GetContext().setauthentication(authentication); System. out.println("Set Authentication with empty token"); }} filterchain.DoFilter(ServletRequest, Servletresponse); }@Override     Public void Destroy(){    }}
Securitypermissionevalutor.java
/*** @author: Blaketairan */import org.springframework.beans.factory.annotation.Autowired;import Org.springframework.security.access.PermissionEvaluator;import org.springframework.security.core.Authentication;import java.io.Serializable;/*** Description:spring-security Custom rights processing module (authentication) */ Public classSecuritypermissionevaluatorImplementsPermissionevaluator {@Override     Public Boolean haspermission(Authentication authentication,object targetdomainobject, Object permission) {String targetdomainobjectstring =NULL; String permissionstring =NULL; String token =NULL;Try{targetdomainobjectstring = (String) targetdomainobject;            permissionstring = (String) permission; token = (String) authentication.getcredentials(); }Catch(ClassCastException e) {e.Printstacktrace();return false; }return haspermission(token, targetdomainobjectstring, permissionstring); }@Override     Public Boolean haspermission(Authentication authentication, Serializable Targetid, String targetType, Object permission) {/*** Use @preauthorize ("haspermission (' TARGET ', ' PERMISSION ')") method, do not use the authentication logic         */        return false; }Private Boolean haspermission(String token,string targetdomain, string permission) {/*** Verify Permissions        **/        return true; }}
Securityconfig.java Global Configuration
/*** @author: Blaketairan */import Org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import Org.springframework.security.access.PermissionEvaluator;import Org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import Org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;/*** description:spring-security configuration, specifying the use of a custom permission evaluation method */@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prepostenabled =true) Public classSecurityconfigextendswebsecurityconfigureradapter{@Bean    @Override    protectedAuthenticationManagerAuthenticationManager()throwsexception{return Super.AuthenticationManager(); }@Bean     PublicPermissionevaluatorPermissionevaluator() {/*** Use custom permission validation        **/Securitypermissionevaluator Securitypermissionevaluator =New Securitypermissionevaluator();returnSecuritypermissionevaluator; }@Override    protected void Configure(Httpsecurity httpsecurity)throwsexception{/*** switch off csrf convenient local IP call debugging        **/Httpsecurity.CSRF()                .Disable()                .Httpbasic()                .Disable(); }}
Baserepository.java a method that requires permission validation
/** * @author: Blaketairan */import org.springframework.security.access.prepost.PreAuthorize;import java.util.List;/** * Description:  */publicinterface BaseRepository{    @PreAuthorize("hasPermission(‘DOMAIN‘, ‘PERMISSION‘)")    voiddeleteAll();}
Conclusion

Hope to be helpful to those who see this article.

Springsecurity for Custom token checking

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.