最近再学习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

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

  1. Spring Security OAuth2.0认证授权六:前后端分离下的登录授权

    历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...

  2. 【Spring Cloud & Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权

    一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证授权.鉴权的逻辑,结合 ...

  3. Spring Security OAuth2.0认证授权二:搭建资源服务

    在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...

  4. Spring Security OAuth2.0认证授权三:使用JWT令牌

    Spring Security OAuth2.0系列文章: Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二: ...

  5. Spring Security OAuth2.0认证授权五:用户信息扩展到jwt

    历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...

  6. Spring Security OAuth2.0认证授权四:分布式系统认证授权

    Spring Security OAuth2.0认证授权系列文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授 ...

  7. Spring Security + OAuth2 + JWT 基本使用

    Spring Security + OAuth2 + JWT 基本使用 前面学习了 Spring Security 入门,现在搭配 oauth2 + JWT 进行测试. 1.什么是 OAuth2 OA ...

  8. Springboot集成Spring Security实现JWT认证

    我最新最全的文章都在南瓜慢说 www.pkslow.com,欢迎大家来喝茶! 1 简介 Spring Security作为成熟且强大的安全框架,得到许多大厂的青睐.而作为前后端分离的SSO方案,JWT ...

  9. Springboot WebFlux集成Spring Security实现JWT认证

    我最新最全的文章都在南瓜慢说 www.pkslow.com,欢迎大家来喝茶! 1 简介 在之前的文章<Springboot集成Spring Security实现JWT认证>讲解了如何在传统 ...

随机推荐

  1. "《算法导论》之‘线性表’":基于静态分配的数组的顺序表

    首先,我们来搞明白几个概念吧(参考自网站数据结构及百度百科). 线性表 线性表是最基本.最简单.也是最常用的一种数据结构.线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外, ...

  2. gtk程序运行报 main_loop!=NULL 错误的解决办法

    现象是将按钮的clicked Action与gtk_main_quit函数绑定起来会发生如上错误. 原因不明. 如果将window的destroy Action与gtk_main_quit绑定是没有问 ...

  3. 关于SharePoint2007简单随感

    首先,还是要感谢我毕业以后的这第一份正式工作,当然现在也依然在做,带我走进了SharePoint的世界,很奇妙也许是有缘吧,自己不是个努力的人,从面试的时候对Moss这个东西闻所未闻,到现在一知半解, ...

  4. Hadoop DataNode不能正常工作的原因

    在把Hadoop环境搭建成功,并且也Hadoop的各个组件都正常工作.在重启过几次Hadoop后发现DataNode不能正常工作,打开Hadoop 的后台http://localhost:50030和 ...

  5. SharePoint 入门级介绍

    前言:接触SharePoint两年有余,从一开始的小白,变成现在的菜鸟,一路走来,学到很多,现在,想把自己知道的东西,写给大家,尤其是刚刚接触SharePoint的人们,做一个简单的参考.从一开始接触 ...

  6. how tomcat works 读书笔记 十一 StandWrapper 上

    方法调用序列 下图展示了方法调用的协作图:  这个是前面第五章里,我画的图:  我们再回顾一下自从连接器里  connector.getContainer().invoke(request, resp ...

  7. 从ruby实现时间服务器ntp同步功能也谈“逆向工程”

    本猫以前写asm和C的时候常常不忘"逆向"一把,后来写驱动的时候也用VM之类的搭建"双机"调试环境进行调试:也对于一些小的软件crack cd-key神马的不亦 ...

  8. MOOS学习笔记4——独立线程不同回调

    MOOS学习笔记4--独立线程不同回调 /** * @fn 独立线程不同回调 * @version v1.0 * @author */ #include "MOOS/libMOOS/Comm ...

  9. Jhipster 学习(一)jhipster构建项目

    如何安装jhipster 第一步:下载jdk  自己安装的1.8版本  (安装.环境变量配置略) 第二步:1.下载Eclipse (luna版 eclipse-4.4.1) 第三步:下载maven ( ...

  10. jsp面试题

    1, JSP中有那些内置对象,以及作用? 共有9种基本内置组件: request 用户端请求,此请求会包含来自GET/POST请求的参数: response 网页传回用户端的回应: pageConte ...