赞
踩
Oauth2提供的默认端点
===============================================================================================
注:grant_type、scope、client_id需要和AuthorizationServerConfig中配置的一样
1.模式获取access_token
2.刷新access_token
3.访问受保护的资源
http://localhost:8080/order/1?access_token=b3d2c131-1225-45b4-9ff5-51ec17511cee
===============================================================================================
security oauth2 整合的3个核心配置类
===============================================================================================
pom.xml
- <dependencies>
- <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.6.RELEASE</version>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>8.0.17</version>
- </dependency>
-
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.1.2</version>
- </dependency>
-
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <optional>true</optional>
- </dependency>
-
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>4.6.1</version>
- <scope>test</scope>
- </dependency>
- </dependencies>

===============================================================================================
认证授权配置AuthorizationServerConfigurerAdapter.java
- package com.kejin.oauth2test.config;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.connection.RedisConnectionFactory;
- import org.springframework.http.HttpMethod;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.core.userdetails.UserDetailsService;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
- import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
- import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
- import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
- import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
- import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
-
- @Configuration
- @EnableAuthorizationServer
- public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
-
- private static final String RESOURCE_IDS = "order";
-
- @Autowired
- AuthenticationManager authenticationManager;
-
- @Autowired
- RedisConnectionFactory redisConnectionFactory;
-
- @Autowired
- private UserDetailsService userDetailsService;
-
- @Override
- public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
-
- String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode("123456");
- //配置两个客户端,一个用于password认证一个用于client认证
- clients.inMemory()
-
- //client模式
- .withClient("client_1")
- .authorizedGrantTypes("client_credentials", "refresh_token")
- .scopes("select")
- .authorities("oauth2")
- .secret(finalSecret)
-
- .and()
-
- //密码模式
- .withClient("client_2")
- .authorizedGrantTypes("password", "refresh_token")
- .scopes("select")
- .authorities("oauth2")
- .secret(finalSecret);
- }
-
- /**
- * 认证服务端点配置
- */
- @Override
- public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
- endpoints
- //用户管理
- .userDetailsService(userDetailsService)
- //token存到redis
- .tokenStore(new RedisTokenStore(redisConnectionFactory))
- //启用oauth2管理
- .authenticationManager(authenticationManager)
- //接收GET和POST
- .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
- }
-
- @Override
- public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
- oauthServer.allowFormAuthenticationForClients();
- }
-
- }

===============================================================================================
security 配置 WebSecurityConfig
- package com.kejin.oauth2test.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
- import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
- import org.springframework.security.crypto.factory.PasswordEncoderFactories;
- import org.springframework.security.crypto.password.PasswordEncoder;
-
- @Configuration
- @EnableWebSecurity
- public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
-
- @Bean
- PasswordEncoder passwordEncoder() {
- return PasswordEncoderFactories.createDelegatingPasswordEncoder();
- }
-
- /**
- * 注入AuthenticationManager接口,启用OAuth2密码模式
- *
- * @return
- * @throws Exception
- */
- @Bean
- @Override
- public AuthenticationManager authenticationManagerBean() throws Exception {
- AuthenticationManager manager = super.authenticationManagerBean();
- return manager;
- }
-
- /**
- * 通过HttpSecurity实现Security的自定义过滤配置
- *
- * @param httpSecurity
- * @throws Exception
- */
- @Override
- protected void configure(HttpSecurity httpSecurity) throws Exception {
- httpSecurity
- .requestMatchers().anyRequest()
- .and()
- .authorizeRequests()
- .antMatchers("/oauth/**").permitAll();
- }
- }

===============================================================================================
AuthUser
- package com.kejin.oauth2test.entity;
-
- import lombok.Data;a
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.userdetails.User;
-
- import java.util.Collection;
-
- @Data
- public class AuthUser extends User {
-
- private Integer id;
-
- public AuthUser(Integer id,
- String username,
- String password,
- boolean enabled,
- boolean accountNonExpired,
- boolean credentialsNonExpired,
- boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
- super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
- this.id = id;
- }
- }

===============================================================================================
获取用户信息UserDetailsServiceImplement
- package com.kejin.oauth2test.service.impl;
-
- import com.kejin.oauth2test.entity.AuthUser;
- import com.kejin.oauth2test.entity.User;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.core.userdetails.UserDetailsService;
- import org.springframework.security.core.userdetails.UsernameNotFoundException;
- import org.springframework.stereotype.Service;
-
- import java.util.Collection;
-
- @Service
- public class UserDetailsServiceImpl implements UserDetailsService {
-
- @Autowired
- private UserServiceImpl userService;
-
- /**
- * 实现UserDetailsService中的loadUserByUsername方法,用于加载用户数据
- */
- @Override
- public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- User user = userService.queryUserByUsername(username);
- if (user == null) {
- throw new UsernameNotFoundException("用户不存在");
- }
-
- //用户权限列表
- Collection<? extends GrantedAuthority> authorities = userService.queryUserAuthorities(user.getId());
-
- return new AuthUser(
- user.getId(),
- user.getUsername(),
- user.getPassword(),
- true,
- true,
- true,
- true,
- authorities);
- }
- }

===============================================================================================
application.yml
- server:
- port: 8080
-
- spring:
- thymeleaf:
- encoding: UTF-8
- cache: false
-
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
- username: root
- password: root12
-
- redis:
- host: 127.0.0.1
- port: 6379
- password:
-
- logging.level.org.springframework.security: DEBUG

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。