Moment For Technology

Spring Security Oauth2 permitAll(

Posted on Jan. 31, 2023, 2:16 p.m. by Shlok Barad
Category: The back-end Tag: The back-end java security spring

The weasel set up a tablet on the cliff of the chicken farm, writing: "If you don't fly down bravely, how do you know you are an eagle fighting in the sky? !"

From then on

Weasels eat dead chickens every day at the bottom of the cliff!

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/21/16382fb353742b5b~tplv-t2oaga2asx-image.image

preface

AntMatchers ("/permitAll").permitall (), But if the Authorization in the header Bearer XXXX, OAuth2AuthenticationProcessingFilter will go to check the correctness of the Token, if the Token is legal, can normal visit, otherwise, the attempt failed. His requirement is that when configuring.permitall (), it can be accessed directly, even if it carries a Token.

solution

According to Spring Security source analysis a: Spring Security authentication process that Spring - Security authentication for a series of filter chain. We need to define a filter interceptor specified request earlier than OAuth2AuthenticationProcessingFilter, remove the Authorization in the header Bearer XXXX.

Code changes

Add PermitAuthenticationFilter class

Add PermitAuthenticationFilter class interceptor specified request, to empty the Authorization header Bearer XXXX

@Component("permitAuthenticationFilter")
@Slf4j
public class PermitAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        log.info("Currently accessed address :{}", request.getRequestURI());
        if ("/permitAll".equals(request.getRequestURI())) {

            request = new HttpServletRequestWrapper(request) {
                private SetString headerNameSet;

                @Override
                public EnumerationString getHeaderNames(a) {
                    if (headerNameSet == null) {
                        // first time this method is called, cache the wrapped request's header names:
                        headerNameSet = new HashSet();
                        EnumerationString wrappedHeaderNames = super.getHeaderNames();
                        while (wrappedHeaderNames.hasMoreElements()) {
                            String headerName = wrappedHeaderNames.nextElement();
                            if (!"Authorization".equalsIgnoreCase(headerName)) { headerNameSet.add(headerName); }}}return Collections.enumeration(headerNameSet);
                }

                @Override
                public EnumerationString getHeaders(String name) {
                    if ("Authorization".equalsIgnoreCase(name)) {
                        return Collections.StringemptyEnumeration();
                    }
                    return super.getHeaders(name);
                }

                @Override
                public String getHeader(String name) {
                    if ("Authorization".equalsIgnoreCase(name)) {
                        return null;
                    }
                    return super.getHeader(name); }}; } filterChain.doFilter(request, response); }}Copy the code

Add the PermitAllSecurityConfig configuration

Add PermitAllSecurityConfig configuration is used to configure PermitAuthenticationFilter

@Component("permitAllSecurityConfig")
public class PermitAllSecurityConfig extends SecurityConfigurerAdapterDefaultSecurityFilterChain.HttpSecurity {

    @Autowired
    private Filter permitAuthenticationFilter;

    @Override
    public void configure(HttpSecurity http) throws Exception { http.addFilterBefore(permitAuthenticationFilter, OAuth2AuthenticationProcessingFilter.class); }}Copy the code

Modify MerryyouResourceServerConfig, increase authorization to the set path

 @Override
    public void configure(HttpSecurity http) throws Exception {

        // @formatter:off
        http.formLogin()
                .successHandler(appLoginInSuccessHandler)// Successful login handler
                .and()
                .apply(permitAllSecurityConfig)
                .and()
                .authorizeRequests()
                .antMatchers("/user").hasRole("USER")
                .antMatchers("/forbidden").hasRole("ADMIN")
                .antMatchers("/permitAll").permitAll()
                .anyRequest().authenticated().and()
                .csrf().disable();

        // @formatter:ON
    }
Copy the code
  • For instructions on each path reference: Test the Spring Security Oauth2 API with Spring MVC

Example Modify the test class SecurityOauth2Test

Add the permitAllWithTokenTest method

    @Test
    public void permitAllWithTokenTest(a) throws Exception{
        final String accessToken = obtainAccessToken();
        log.info("access_token={}", accessToken);
        String content = mockMvc.perform(get("/permitAll").header("Authorization"."bearer " + accessToken+"11"))
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
        log.info(content);
    }
Copy the code
  • Authorization bearer xxx 11It's followed by two random parameters

Results the following

When permitAllSecurityConfig is not configured

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/21/16382fc5a913c492~tplv-t2oaga2asx-image.image

When configuring permitAllSecurityConfig

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/21/16382fc5a927dc2f~tplv-t2oaga2asx-image.image

The code download

  • Github:github.com/longfeizhen...
  • Gitee:gitee.com/merryyou/se...

Recommend the article

  1. Java creates the blockchain family
  2. Spring Security source code analysis series
  3. Spring Data Jpa series
  4. All about Trees in Data Structures (Java Edition)
  5. SpringBoot+Docker+Git+Jenkins realize easy continuous integration and continuous deployment

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/16/16367d5da0881498~tplv-t2oaga2asx-image.image

??? focus on wechat small program Java architect journey Bored on the commute? Still reading novels, news? Don't know how to improve your skills? Here's the Java architecture article you need. 1.5W + Java engineers are reading it. What are you waiting for?

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.