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 11
followed 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
- Java Create block chain series
- Spring Security Source Analysis series
- Spring Data JPA Series
- Everything about trees in the "translated" Data Structure (Java edition)
- 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