簡體   English   中英

如何針對這種情況配置HttpSecurity(Spring Boot)

[英]How to configure HttpSecurity for this situation (Spring Boot)

條件:

  • 未經身份驗證的用戶從/ oauth / token請求令牌
  • 未經身份驗證的用戶還可以通過/swagger-ui.html訪問swagger文檔。
  • 所有其他端點都應受到保護,即要求使用有效令牌。

我嘗試過的

SecurityConfig.java-可能是問題的根源

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.authenticationProvider(customAuthenticationProvider);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .antMatcher("/oauth/token")
                .addFilterBefore(new RESTAuthenticationTokenProcessingFilter(), BasicAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .anyRequest().authenticated();

    }
}

CustomAuthenticationProvider.java

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    final
    UserService userService;

    final
    TokenService tokenService;

    @SuppressWarnings("SpringJavaAutowiredMembersInspection")
    @Autowired
    public CustomAuthenticationProvider(TokenService tokenService, UserService userService) {
        this.tokenService = tokenService;
        this.userService = userService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        Object credentials = authentication.getCredentials();
        if (!(credentials instanceof String)) return null;
        String password = credentials.toString();
        // TODO implement hashing and salting of passwords
        UserDetails user = userService.loadUserByUsername(username);
        if (!user.getPassword().equals(password)) throw new NotAuthorisedException(AuthorisationFailureTypes.INVALID_REQUEST);

        TokenModel tokenModel = tokenService.allocateToken(user.getUsername());
        authentication.setAuthenticated(true);
        return authentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return TokenRequestModel.class.isAssignableFrom(authentication);
    }
}

RESTAuthenticationTokenProcessingFilter.java

@Component
public class RESTAuthenticationTokenProcessingFilter extends GenericFilterBean {

    public RESTAuthenticationTokenProcessingFilter() {
    }

    public RESTAuthenticationTokenProcessingFilter(UserService userService, String restUser) {
        this.userService = userService;
        this.REST_USER = restUser;
    }

    @Autowired
    private TokenService tokenService;
    private UserService userService;
    private String REST_USER;
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = getAsHttpRequest(request);
        String authToken = extractAuthTokenFromRequest(httpRequest);
        if (authToken == null) throw new NotAuthorisedException(AuthorisationFailureTypes.INVALID_REQUEST);

        String[] parts = authToken.split(" ");

        if (parts.length == 2) {
            String tokenKey = parts[1];
            if (validateTokenKey(tokenKey)) {
                TokenModel token = tokenService.getTokenById(tokenKey);
                //List<String> allowedIPs = new Gson().fromJson(token.getAllowedIP(), new TypeToken<ArrayList<String>>() {}.getType());
                //if (isAllowIP(allowedIPs, request.getRemoteAddr())) {
                if (token != null) {
                    if (token.getExpires_in() > 0) {
                        UserDetails userDetails = userService.loadUserByUsername(REST_USER);
                        TokenRequestModel authentication = new TokenRequestModel(null, null, userDetails.getUsername(), userDetails.getPassword());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        log.info("Authenticated " + token.getAccess_token() + " via IP: " + request.getRemoteAddr());
                    } else {
                        log.info("Unable to authenticate the token: " + authToken + ". Incorrect secret or token is expired");
                        throw new NotAuthorisedException(AuthorisationFailureTypes.INVALID_REQUEST);
                    }
                    //} else {
                    //log.info("Unable to authenticate the token: " + authToken + ". IP - " + request.getRemoteAddr() + " is not allowed");l
                }
            }
        } else {
            log.info("Unable to authenticate the token: " + authToken + ". Key is broken");
            throw new NotAuthorisedException(AuthorisationFailureTypes.INVALID_REQUEST);
        }
        chain.doFilter(request, response);
    }

    private boolean validateTokenKey(String tokenKey) {
        String[] parts = tokenKey.split("-");
        return parts.length == 5;
    }

    private HttpServletRequest getAsHttpRequest(ServletRequest request) {
        if (!(request instanceof HttpServletRequest)) {
            throw new RuntimeException("Expecting an HTTP request");
        }

        return (HttpServletRequest) request;
    }


    private String extractAuthTokenFromRequest(HttpServletRequest httpRequest) {
    // Get token from header

    String authToken = httpRequest.getHeader("authorisation");

    // If token not found get it from request parameter

    if (authToken == null) {
        authToken = httpRequest.getParameter("access_token");
    }

    return authToken;
    }
}

結果是,任何使用“授權”標頭發出請求的用戶都可以訪問所有資源。 並且沒有Authorization標頭的用戶不能請求使用令牌。

我花了很多時間嘗試從其他示例中提取信息,並從HTTPSecurity類及其相關類通讀了Docs,但是我無法理解如何實現此配置。

任何幫助將不勝感激!

編輯-

由於該項目的性質,我必須遵循一個協議,該協議涉及略微簡化的oauth2版本。 不幸的是,這意味着要實現Spring Security中已經提供的很多功能(即,我無法使用Spring-Security-oauth2或Spring Security 5)。 滿足我的特定需求。 我真的很感謝您有任何建議。

我從一個教程中找到了一個解決方案,該解決方案涉及實現自己的整個授權過程版本。 但這有效!

我的SecurityConfig.java類變為:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private final AuthenticationSuccessHandler loginSuccessfulHandler;
private final AuthenticationFailureHandler loginFailureHandler;
private final AccessDeniedHandler customAccessDeniedHandler;
private final AuthenticationEntryPoint customAuthenticationEntryPoint;

@Autowired
public SecurityConfig(AuthenticationSuccessHandler loginSuccessfulHandler, AuthenticationFailureHandler loginFailureHandler, AccessDeniedHandler customAccessDeniedHandler, AuthenticationEntryPoint customAuthenticationEntryPoint) {
    this.loginSuccessfulHandler = loginSuccessfulHandler;
    this.loginFailureHandler = loginFailureHandler;
    this.customAccessDeniedHandler = customAccessDeniedHandler;
    this.customAuthenticationEntryPoint = customAuthenticationEntryPoint;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
            .withUser("user").password("password").roles("USER")
            .and()
            .withUser("admin").password("password").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable() // disable CSRF for this application
            .formLogin() // Using form based login instead of Basic Authentication
            .loginProcessingUrl("/oauth/token") // Endpoint which will process the authentication request. This is where we will post our credentials to authenticate
            .successHandler(loginSuccessfulHandler)
            .failureHandler(loginFailureHandler)
            .and()
            .authorizeRequests()
            .antMatchers("/oauth/token").permitAll() // Enabling URL to be accessed by all users (even un-authenticated)
            .antMatchers("/swagger-ui.html").permitAll()
             //.antMatchers("/secure/admin").access("hasRole('ADMIN')") // Configures specified URL to be accessed with user having role as ADMIN
            .anyRequest().authenticated() // Any resources not mentioned above needs to be authenticated
            .and()
            .exceptionHandling().accessDeniedHandler(customAccessDeniedHandler)
            .authenticationEntryPoint(customAuthenticationEntryPoint)
            .and()
            .anonymous().disable(); // Disables anonymous authentication with anonymous role.
}

因此,我必須通過實現現有接口來實現我的登錄(成功/失敗)處理程序等。 現在,我只需要實現自己的AuthenticationMangager而不是當前使用的內存中配置即可。

@dur感謝您的幫助! :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM