简体   繁体   中英

Spring Security with oAuth2.0 and form login

In my Spring Boot application, i am having form based login and oAuth2.0 based login with Google, my security configuration is defined as

http
    .cors()
        .and()
    .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
    .csrf().disable()
    .authorizeRequests()
        .antMatchers("/oauth2/**").permitAll()
        .anyRequest().authenticated()
        .and()
    .addFilter(new JWTAuthenticationFilter(authenticationManager()))
    .addFilter(jwtAuthorizationFilter)
    .formLogin()
        .and()
    .oauth2Login()
        .authorizationEndpoint()
            .authorizationRequestRepository(httpCookieOAuth2AuthorizationRequestRepository)
            .and()
        .userInfoEndpoint()
            .userService(customOAuth2UserService)
            .and()
        .successHandler(oAuth2AuthenticationSuccessHandler)
            .failureHandler(oAuth2AuthenticationFailureHandler);

I am doing stateless authentication with JWT, for form based login JWTAuthenticationFilter handles the authentication as below.

JWTAuthenticationFilter

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    //code to authenticate user and generate JWT
}

and JWTAuthorizationFilter validates the JWT for subsequent requests as below.

JWTAuthorizationFilter

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    // code to perform authorization
}

Now coming to OAuth2.0 customOAuth2UserService does register the new users and update the existing user information. OAuth2AuthenticationSuccessHandler generates JWT on successful OAuth2.0 authentication. Now functionality wise both form login and OAuth2.0 works fine, but there are few tiny issues I am trying to solve which I need help for.

Issues

  1. If I hit http://localhost:8080/login with wrong form login credentials I am getting a sign in HTML form with Google login as response body and 200 as status code, ideally I want 400 bad request or something.
  2. When I don't provide a JWT token along with request, I am getting the same HTML response body with 200 status code, ideally I would like a 401 for that as well.

What configurations I am missing and what can I change to fix these issues.

for 2nd issue you can add this for HTTP security config

.exceptionHandling().authenticationEntryPoint(jwtUnAuthorizedResponseAuthenticationEntryPoint)

and then autowire the jwtUnAuthorizedResponseAuthenticationEntryPoint in the class and define the JwtUnAuthorizedResponseAuthenticationEntryPoint class like this

import java.io.IOException;
import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

@Component
public class JwtUnAuthorizedResponseAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    // they is always a generic message that is showed when the unauthenticated user
    // user makes a request
    // here in this class we will override and show what we want to show to an
    // unauthorized user
    // this is called internally

    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "You would need to provide the Jwt Token to Access This resource");
    }
}

it will throw the 401 error that you want as

public static final int SC_UNAUTHORIZED = 401;

in public interface HttpServletResponse extends ServletResponse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM