spring security oauth2 jwt 认证和资源分离的配置文件(java类配置版)

最近再学习spring security oauth2。下载了官方的例子sparklr2和tonr2进行学习。但是例子里包含的东西太多,不知道最简单最主要的配置有哪些。所以决定自己尝试搭建简单版本的例子。学习的过程中搭建了认证和资源在一个工程的例子,将token存储在数据库的例子等等 。最后做了这个认证和资源分离的jwt tokens版本。网上找了一些可用的代码然后做了一个整理, 同时测试了哪些代码是必须的。可能仍有一些不必要的代码在,欢迎大家赐教。

一.创建三个spring boot 工程,分别添加必要的依赖。认证和资源的工程需要添加依赖        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-jwt</artifactId>
            <version>1.0.7.RELEASE</version>
        </dependency>

二资源端工程的资源配置文件:

@Configuration
@EnableResourceServer
public class OAuth2ResourceService extends ResourceServerConfigurerAdapter {
    private static final String SPARKLR_RESOURCE_ID = "apple";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.tokenServices(tokenServices()).resourceId(SPARKLR_RESOURCE_ID);
    }
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("123");
        return converter;
    }
    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
            http
                .authorizeRequests()
                .antMatchers("/hello").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))");  
        // @formatter:on
    }
}

安全配置文件:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
            .authorizeRequests()
                .antMatchers("/hello").hasRole("USER")
                .and().csrf().disable()
                .formLogin().loginPage("/login").failureUrl("/login-error");
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("hello").password("123").roles("USER");
    }
}

三 认证端工程的认证配置文件:

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    private static final String SPARKLR_RESOURCE_ID = "apple";
    
    int accessTokenValiditySeconds = 3600;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;
    
       @Bean
        public JwtAccessTokenConverter accessTokenConverter() {
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
            converter.setSigningKey("123");
            return converter;
        }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        // @formatter:off
        clients.inMemory().withClient("tonr")
                     .resourceIds(SPARKLR_RESOURCE_ID)
                     .authorizedGrantTypes("authorization_code", "implicit")
                     .authorities("ROLE_CLIENT")
                     .scopes("read", "write")
                     .secret("secret")
                     .accessTokenValiditySeconds(accessTokenValiditySeconds);
        // @formatter:on
    }
    //jdbc
//    @Bean
//    public DataSource jdbcTokenDataSource(){
//        DriverManagerDataSource dataSource = new DriverManagerDataSource();
//        dataSource.setDriverClassName("com.MySQL.jdbc.Driver");
//        dataSource.setUrl("jdbc:mysql://localhost/test");
//        dataSource.setUsername("root");
//        dataSource.setPassword("root");
//        return dataSource;
//    }
    
    @Bean
    public TokenStore tokenStore() {
//        return new InMemoryTokenStore();
//        return new JdbcTokenStore(jdbcTokenDataSource());
         return new JwtTokenStore(accessTokenConverter());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore())
        .authenticationManager(this.authenticationManager)
        .accessTokenConverter(accessTokenConverter());
    }
       @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
            defaultTokenServices.setTokenStore(tokenStore());
            defaultTokenServices.setSupportRefreshToken(true);
            return defaultTokenServices;
        }
}\

spring security安全配置文件:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
            .authorizeRequests()
            .antMatchers("/css/**", "/index").permitAll()
            .and()
            .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
                .formLogin().loginPage("/login").failureUrl("/login-error");
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("hello").password("123").roles("USER");
    }
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

四 客户端工程的配置文件:

@Configuration
@EnableOAuth2Client
public class ResourceConfiguration {

    @Bean
    public OAuth2ProtectedResourceDetails hello() {
        AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
        details.setId("hello");
        details.setClientId("tonr");
        details.setClientSecret("secret");
        details.setAccessTokenUri("http://localhost:8083/auth/oauth/token");//认证服务器地址+/oauth/token
        details.setUserAuthorizationUri("http://localhost:8083/auth/oauth/authorize");//认证服务器地址+/oauth/authorize
        details.setScope(Arrays.asList("read", "write"));
        return details;
    }

    @Bean
    public OAuth2RestTemplate helloRestTemplate(OAuth2ClientContext oauth2Context) {//客户端的信息被封装到OAuth2RestTemplate用于请求资源
        return new OAuth2RestTemplate(hello(), oauth2Context);
    }
}

在业务逻辑的serviceImp类中 注入helloRestTemplate 然后:

    @Autowired
    private RestOperations helloRestTemplate

public String getDataFromResoureServer() {;

String data= helloRestTemplate.getForObject(URI.create("http://localhost:8080/resource/hello"), String.class);//请求资源服务器资源的路径

return data;

}

spring security安全配置文件:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/css/**", "/index").permitAll()      
                .and()
            .formLogin()
                .loginPage("/login").failureUrl("/login-error");    
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("insecure").password("123").roles("USER");
    }
}

 

http://blog.csdn.net/u010139801/article/details/68484090

 

时间: 2024-08-04 00:46:25

spring security oauth2 jwt 认证和资源分离的配置文件(java类配置版)的相关文章

Spring Security OAuth2实现使用JWT

1.概括 在博客中,我们将讨论如何让Spring Security OAuth2实现使用JSON Web Tokens. 2.Maven 配置 首先,我们需要在我们的pom.xml中添加spring-security-jwt依赖项. <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-jwt</artifactId> &l

Spring Security OAuth2 Demo -- good

1. 添加依赖授权服务是基于Spring Security的,因此需要在项目中引入两个依赖: <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-security</artifactId> </dependency> <dependency> <groupId>org.springf

Spring Security OAuth2 Demo

Spring Security OAuth2 Demo 项目使用的是MySql存储, 需要先创建以下表结构: CREATE SCHEMA IF NOT EXISTS `alan-oauth` DEFAULT CHARACTER SET utf8 ; USE `alan-oauth` ; -- ----------------------------------------------------- -- Table `alan-oauth`.`clientdetails` -- --------

授权-求OpenID整合spring security oauth2 实例

问题描述 求OpenID整合spring security oauth2 实例 客户端利用openID作身份验证,然后绑定Oauth授权服务器,获取资源

spring security oauth2

  https://connect.qq.com/manage.html#/   Spring Boot Oauth2 with H2 databasehttps://github.com/rajithd/spring-boot-oauth2 使用oauth2.0写的简单的client和认证Server,使用了@EnableOAuth2Sso注解来模拟单点登陆https://github.com/jiangchao123/oauthserver Spring-Boot projects usin

使用JWT保护你的Spring Boot应用 - Spring Security实战

作者 freewolf 原创文章转载请标明出处 关键词 Spring Boot.OAuth 2.0.JWT.Spring Security.SSO.UAA 写在前面 最近安静下来,重新学习一些东西,最近一年几乎没写过代码.整天疲于奔命的日子终于结束了.坐下来,弄杯咖啡,思考一些问题,挺好.这几天有人问我Spring Boot结合Spring Security实现OAuth认证的问题,写了个Demo,顺便分享下.Spring 2之后就没再用过Java,主要是xml太麻烦,就投入了Node.js的怀

Spring Boot中集成Spring Security 专题

if语句中条件判断就是检查当前的url请求是否是logout-url的配置值,接下来,获取用户的authentication,并循环调用处理器链中各个处理器的logout()函数,前面在parse阶段说过,处理器链中有两个实例,处理会话的SecurityContextLogoutHandler及remember-me服务,我们来一一看看它们的logout函数实现: 2.1.0 SecurityContextLogoutHandler public void logout(HttpServletR

Spring Security 2配置精讲 上

安全权限管理手册 http://www.family168.com/oa/springsecurity/html/ 众所周知,Spring Security针对Acegi的一个重大的改进就在于其配置方式大大简化了.所以如果配置还是基于Acegi-1.X这样比较繁琐的配置方式的话,那么我们还不如直接使用Acegi而不要去升级了.所以在这里,我将结合一个示例,重点讨论一下Spring Security 2是如何进行配置简化的. 搭建基础环境 首先我们为示例搭建基本的开发环境,环境的搭建方式,可以参考

Spring Security 4.0.0.RC2/3.2.6 发布

Spring Security 4.0.0.RC2 发布,此版本解决了大约 50 tickets. 主要改进: Support for enforcing Same Origin for WebSocket connections Refinements in WebSocket Configuration (SEC-2827 SEC-2833 SEC-2853 ) More intuitive HTTP Response Headers Configuration (SEC-2846) GA