Spring Security Oauth2 Permitall () method Small note

Source: Internet
Author: User

Weasel in a chicken farm on the edge of a monument, wrote: "Not brave to fly down, how do you know that you are an eagle to fight the sky?" ”

Since then

The weasel can eat the fallen chickens at the bottom of the cliff every day!

Objective

In Friday, a netizen asked, in use spring-security-oauth2 , although configured .antMatchers("/permitAll").permitAll() , but if carried in header Authorization Bearer xxxx , OAuth2AuthenticationProcessingFilter or will go to verify Token the correctness, if Token legitimate, can be normal access, otherwise, the request failed. His needs are when configured .permitAll() , even if carried Token , can also be accessed directly.

Solution Ideas

According to spring security source Analysis One: The Spring security certification process learned spring-security that the certification is a series of filter chain. We just need to define an OAuth2AuthenticationProcessingFilter earlier filter to intercept the specified request and remove it header Authorization Bearer xxxx .

Code modification Add Permitauthenticationfilter class

The Add PermitAuthenticationFilter class intercepts the specified request, emptying header theAuthorization Bearer xxxx

@Component("Permitauthenticationfilter")@Slf4j Public classPermitauthenticationfilterextendsOnceperrequestfilter {@Override    protected void dofilterinternal(HttpServletRequest request, httpservletresponse response, Filterchain Filterchain)throwsServletexception, IOException {log.Info("currently visited address: {}", request.Getrequesturi());if("/permitall".equals(Request.Getrequesturi())) {request =New Httpservletrequestwrapper(Request) {PrivateSet<string> Headernameset;@Override                 PublicEnumeration<string>Getheadernames() {if(Headernameset = =NULL) {//First time this method is called, cache the wrapped request ' s header names:Headernameset =NewHashset<> (); Enumeration<string> Wrappedheadernames =Super.Getheadernames(); while(Wrappedheadernames.hasmoreelements()) {String headername = wrappedheadernames.nextelement();if(!"Authorization".Equalsignorecase(Headername)) {Headernameset.Add(Headername); }                        }                    }returnCollections.Enumeration(Headernameset); }@Override                 PublicEnumeration<string>getheaders(String name) {if("Authorization".Equalsignorecase(name)) {returnCollections.<string>emptyenumeration(); }return Super.getheaders(name); }@Override                 PublicStringGetHeader(String name) {if("Authorization".Equalsignorecase(name)) {return NULL; }return Super.GetHeader(name);        }            }; } filterchain.DoFilter(Request, response); }}
Add Permitallsecurityconfig Configuration

Add PermitAllSecurityConfig configuration for configuringPermitAuthenticationFilter

@Component("permitAllSecurityConfig")publicclassextends SecurityConfigurerAdapter<DefaultSecurityFilterChain,HttpSecurity> {    @Autowired    private Filter permitAuthenticationFilter;    @Override    publicvoidconfigurethrows Exception {        http.addFilterBefore(permitAuthenticationFilter, OAuth2AuthenticationProcessingFilter.class);    }}
Modify Merryyouresourceserverconfig to increase authorization for path development
 @Override     Public void Configure(httpsecurity http)throwsException {//@formatter: Offhttp.Formlogin()                .Successhandler(Applogininsuccesshandler)//Login Successful processor. and()                .Apply(Permitallsecurityconfig). and()                .authorizerequests()                .antmatchers("/user").Hasrole("USER")                .antmatchers("/forbidden").Hasrole("ADMIN")                .antmatchers("/permitall").Permitall()                .anyrequest().Authenticated(). and()                .CSRF().Disable();//@formatter: on}
    • A description of each path reference: Use spring MVC to test the spring Security Oauth2 API
Modify the test class Securityoauth2test

Add permitAllWithTokenTest method

    @Test     Public void permitallwithtokentest()throwsexception{FinalString Accesstoken =Obtainaccesstoken(); Log.Info("access_token={}", Accesstoken); String content = Mockmvc.Perform(Get("/permitall").Header("Authorization","Bearer"+ accesstoken+"One"))                .Andexpect(Status().isOk())                .Andreturn().GetResponse().getcontentasstring(); Log.Info(content); }
    • Authorization bearer xxx 11followed by a random two parameters.
The effect is as follows when Permitallsecurityconfig is not configured

When configuring Permitallsecurityconfig

Code download
    • Github:https://github.com/longfeizheng/security-oauth2
    • Gitee:https://gitee.com/merryyou/security-oauth2
Featured Articles
    1. Java Create block chain series
    2. Spring Security Source Analysis series
    3. Spring Data JPA Series
    4. Everything about trees in the "translated" Data Structure (Java edition)
    5. Springboot+docker+git+jenkins for easy continuous integration and continuous deployment

?????? Follow applet Java architect Journey
Is it boring on the way to commute? Are you still reading novels and news? Don't know how to improve your skills? Come on, here are the Java architecture articles you need, 1.5w+ 's Java engineers are looking, what are you waiting for?

Spring Security Oauth2 Permitall () method Small note

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.