一个应用程序中的 Spring Security OAuth2 和 FormLogin [英] Spring Security OAuth2 and FormLogin in a one application

查看:56
本文介绍了一个应用程序中的 Spring Security OAuth2 和 FormLogin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Spring Boot 应用程序中,我有 RESTful API 和 MVC Web 仪表板用于管理.

In my Spring Boot application I have RESTful API and MVC web dashboard for administration.

是否可以在一个应用程序中同时拥有用于 RESTful API 的 Spring Security OAuth2 身份验证/授权(基于令牌,无状态)和用于 Spring MVC Web 仪表板的 FormLogin(有状态)?

Is it possible to have both - Spring Security OAuth2 authentication/authorization(token based, stateless) for RESTful API and FormLogin(stateful) for Spring MVC web dashboard in a one application ?

如何使用 Spring Boot 正确配置它?

How to properly configure it with Spring Boot ?

推荐答案

您需要为基于表单的登录和资源服务器安全表单 REST 端点配置 Web 安全性

You need to configure your web security for form based login and Resource Server Security form REST Endpoints

这是一个使用单点登录的工作配置,授权服务器单独部署.

Here is a working configuration that uses single sign on with an Authorization Server deployed separately.

@Configuration
@EnableOAuth2Sso
@EnableWebSecurity
protected static class ResourceConfiguration extends WebSecurityConfigurerAdapter {

    @Value("${sso.url}")
    private String ssoUrl;

    @Autowired
    private  RedisConnectionFactory redisConnectionFactory;

    @Bean
    protected TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Bean
    @Primary
    protected ResourceServerTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);

        return defaultTokenServices;
    }


    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        OAuth2AuthenticationManager authenticationManager = new OAuth2AuthenticationManager();
        authenticationManager.setTokenServices(tokenServices());
        return authenticationManager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {      
        http.requestMatchers()
        .and().authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers(HttpMethod.GET, "/static/**").permitAll()
            .antMatchers(HttpMethod.GET, "/profile/**").permitAll()
            .antMatchers(HttpMethod.GET, "/services/**").permitAll()
            .anyRequest().authenticated()
        .and().logout()
                .invalidateHttpSession(true)
                .logoutSuccessUrl(ssoUrl+"/logout")
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .deleteCookies("JSESSIONID").invalidateHttpSession(true)
                .permitAll();
    }

}

@Configuration
@EnableResourceServer
@Order(1)
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {



    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("resource-id");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new OAuthRequestedMatcher())
            .authorizeRequests().anyRequest().fullyAuthenticated();

    }
}

private static class OAuthRequestedMatcher implements RequestMatcher {
    public boolean matches(HttpServletRequest request) {
        String auth = request.getHeader("Authorization");
        boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer");
        boolean haveAccessToken = request.getParameter("access_token")!=null;
        return haveOauth2Token || haveAccessToken;
    }
}

这篇关于一个应用程序中的 Spring Security OAuth2 和 FormLogin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆