Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式1
2018-06-20 19:32
971 查看
0. 前言
之前帐号认证用过自己写的进行匹配,现在要学会使用标准了。准备了解和使用这个OAuth2.0协议。
1. 配置
1.1 配置pom.xml
有些可能会用不到,我把我项目中用到的所有包都贴出来。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency>
1.2 配置application.properties
#server server.port=8080 server.servlet.session.timeout=2520000 #redis spring.redis.database=0 spring.redis.host=172.16.23.203 spring.redis.port=6379 spring.redis.password= spring.redis.jedis.pool.max-active=8 spring.redis.jedis.pool.max-wait=60 spring.redis.jedis.pool.max-idle=8 spring.redis.jedis.pool.min-idle=0 spring.redis.timeout=10000
1.3 资源服务器配置
/** * OAuth 资源服务器配置 * @author * @date 2018-05-29 */ @Configuration @EnableResourceServer public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { private static final String DEMO_RESOURCE_ID = "order"; @Override public void configure(ResourceServerSecurityConfigurer resources) { resources.resourceId(DEMO_RESOURCE_ID).stateless(true); } @Override public void configure(HttpSecurity http) throws Exception { // Since we want the protected resources to be accessible in the UI as well we need // session creation to be allowed (it's disabled by default in 2.0.6) http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() .requestMatchers().anyRequest() .and() .anonymous() .and() .authorizeRequests() .antMatchers("/order/**").authenticated();//配置order访问控制,必须认证过后才可以访问 } }
1.4 授权服务器配置
/** * OAuth 授权服务器配置 * @author * @date 2018-05-29 */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { private static final String DEMO_RESOURCE_ID = "order"; @Autowired AuthenticationManager authenticationManager; @Autowired RedisConnectionFactory redisConnectionFactory; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { String finalSecret = "{bcrypt}"+new BCryptPasswordEncoder().encode("123456"); //配置两个客户端,一个用于password认证一个用于client认证 clients.inMemory() .withClient("client_1") .resourceIds(DEMO_RESOURCE_ID) .authorizedGrantTypes("client_credentials", "refresh_token") .scopes("select") .authorities("oauth2") .secret(finalSecret) .and() .withClient("client_2") .resourceIds(DEMO_RESOURCE_ID) .authorizedGrantTypes("password", "refresh_token") .scopes("select") .authorities("oauth2") .secret(finalSecret); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .tokenStore(new RedisTokenStore(redisConnectionFactory)) .authenticationManager(authenticationManager) .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { //允许表单认证 oauthServer.allowFormAuthenticationForClients(); } }
1.5 Spring Security配置
/** * Spring-Security 配置<br> * 具体参考: https://github.com/lexburner/oauth2-demo * @author * @date 2018-05-28 */ @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Bean @Override protected UserDetailsService userDetailsService(){ InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); String finalPassword = "{bcrypt}"+bCryptPasswordEncoder.encode("123456"); manager.createUser(User.withUsername("user_1").password(finalPassword).authorities("USER").build()); finalPassword = "{noop}123456"; manager.createUser(User.withUsername("user_2").password(finalPassword).authorities("USER").build()); return manager; } @Override protected void configure(HttpSecurity http) throws Exception { http .requestMatchers().anyRequest() .and() .authorizeRequests() .antMatchers("/oauth/*").permitAll(); } /** * Spring Boot 2 配置,这里要bean 注入 */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { AuthenticationManager manager = super.authenticationManagerBean(); return manager; } @Bean PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); }
1.6 定义一个资源点
@RestController @RequestMapping(value="/") public class TestController { @RequestMapping(value="order/demo") public YYModel getDemo() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); System.out.println(auth); YYModel yy = new YYModel(); yy.setYy("中文"); yy.setZz(3); return yy; } @GetMapping("/test") public String getTest() { YYModel yy = new YYModel(); yy.setYy("中文"); yy.setZz(3); return yy.toJSONString(); } }
2. 工具测试
参考: http://blog.didispace.com/spring-security-oauth2-xjf-1/
相关文章推荐
- Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式2
- 在Spring-Boot中实现通用Auth认证的几种方式
- spirng-boot中,基于既有的token验证方式,利用spring-security实现权限系统
- Spring Boot整合Spring Security简单实现登入登出从零搭建教程
- 详解在Spring-Boot中实现通用Auth认证的几种方式
- SpringBoot 简单文件上传实现以及jar包方式运行项目
- spring boot 集成quartz 2.0 实现前端动态配置(获取spring上下文)的两种方式,启动数据库中已开启定时任务
- 利用Spring2.0技术实现RMI的成功简单示例
- 基于Spring Boot 2.0 及MongoDB 3.6.2 实现的简单文件共享服务器
- 一个简单的基于注解的 Controller (spring 2.5 annotation 方式实现mvc )
- 理解Spring框架---利用,xml,java反射简单实现Spring
- 利用servlet 实现JAVAWeb访问微信OAuth2.0认证,获取用户信息的实例
- 利用hadoop命令rcc生成Record 一种简单的方式实现自定义的writable对象
- spring.net、castle windsor、unity实现aop、ioc的方式和简单区别
- Spring Boot实战之netty-socketio实现简单聊天室(给指定用户推送消息)
- Spring_Spring_教程13_利用XML实现Aop方式
- Spring--超简单利用quartz实现定时作业 (转)
- spring security 多登陆入口实现方式 以及对spring security认证流程的理解
- JSF2.0+Spring+Hibernate采用注解方式实现
- 一个简单的基于注解的 Controller (spring 2.5 annotation 方式实现mvc )