SpringBoot整合Oauth2快速入门(入坑)
文章目录前言一、什么是Oauth2?二、使用步骤1.引入Maven依赖2.授权服务器项目目录结构:1.授权服务器的security配置代码如下:2.授权服务器Authorize相关配置:1.@EnableAuthorizationServer 该注解切记需要配置哈。3.yml配置3.启动授权服务器后1.使用PostMan来获取Token令牌。这些参数很重要,还是POST请求方式。4.资源服务器模块
文章目录
前言
Oauth2快速入门案例
一、什么是Oauth2?
OAuth2.0是OAuth协议的延续版本,但不向前兼容OAuth 1.0(即完全废止了OAuth1.0)。 OAuth 2.0关注客户端开发者的简易性。要么通过组织在资源拥有者和HTTP服务商之间的被批准的交互动作代表用户,要么允许第三方应用代表用户获得访问的权限。
Oauth2简单的工作流程图:
二、使用步骤
1.引入Maven依赖
代码如下(示例):新建项目模块直接在pom.xml文件中直接引入即可。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--security-->
<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.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
</dependencies>
2.授权服务器项目目录结构:
1.授权服务器的security配置代码如下:
package com.hh.userserviceoauth2.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("zhangsan")
.password(passwordEncoder().encode("123456"))
.authorities("/*");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.csrf()
.disable();
}
}
2.授权服务器Authorize相关配置:
1.@EnableAuthorizationServer 该注解切记需要配置哈。
package com.hh.userserviceoauth2.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
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.AuthorizationServerSecurityConfigurer;
import org.springframework.stereotype.Component;
@Component
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.allowFormAuthenticationForClients()
.checkTokenAccess("permitAll()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("security_appid")
.secret(passwordEncoder.encode("security_secret"))
.authorizedGrantTypes("authorization_code")
.scopes("all")
.resourceIds("security_resource")
.redirectUris("https://www.baidu.com/callback");
}
}
3.yml配置
server:
port: 8110
3.启动授权服务器后
网络请求路径必须这样请求(Oauth框架封装的请求):http://localhost:8110/oauth/authorize?client_id=security_appid&response_type=code
client_id必须是我们上面配置的(withClient里面的数据否则会报错。)
输入上面的请求路径后会被Security框架资源拦截,先登录。在内存中存放用户的数据。切记密码需要使用BCryptPasswordEncoder对象进行加密。
这是登录后的结果
选择 同意 后出现跳转到https://www.baidu.com/callback 目录并且会进行数据回调,如下所示:
1.使用PostMan来获取Token令牌。这些参数很重要,还是POST请求方式。
这样授权服务器就结束了。
4.资源服务器模块搭建和配置
1.目录结构如下:
2.资源服务器配置
1.代码如下:
package com.hh.userserviceoauth2consume.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
@Configuration
@EnableResourceServer
public class ResourceConfig extends ResourceServerConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Primary
public RemoteTokenServices remoteTokenServices() {
RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:8110/oauth/check_token");
remoteTokenServices.setClientId("security_appid");
remoteTokenServices.setClientSecret("security_secret");
return remoteTokenServices;
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("security_resource").stateless(true);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
http.authorizeRequests().anyRequest().authenticated();
}
}
如何配置需要和授权服务器配置相匹配才行。
server:
port: 8111
2.具体需要获取的数据
package com.hh.userserviceoauth2consume.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@RequestMapping("getUserInfo")
@ResponseBody
public String getUserInfo() {
return "get user info ok";
}
}
3.如下请求资源带上Token令牌后就能获取到具体资源了。
最后完成所有整合,希望能帮助到各位。
总结
人生物语:精神是精神生活的灵魂。精神的航向——理想、信念、志向,是决定一个人生活质量、生活色彩的第一要素。
更多推荐
所有评论(0)