Security-OAuth2.0 密码模式之服务端实现
第一步:配置数据库 ,固定创建三张表 ,OAuth2 框架需要默认使用这三张表

我使用的时Mysql,工具为navcat
CREATE TABLE `oauth_access_token` (
`token_id` varchar(256) DEFAULT NULL,
`token` blob,
`authentication_id` varchar(250) NOT NULL,
`user_name` varchar(256) DEFAULT NULL,
`client_id` varchar(256) DEFAULT NULL,
`authentication` blob,
`refresh_token` varchar(256) DEFAULT NULL,
PRIMARY KEY (`authentication_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
----------
CREATE TABLE `oauth_client_details` (
`client_id` varchar(250) NOT NULL,
`resource_ids` varchar(256) DEFAULT NULL,
`client_secret` varchar(256) DEFAULT NULL,
`scope` varchar(256) DEFAULT NULL,
`authorized_grant_types` varchar(256) DEFAULT NULL,
`web_server_redirect_uri` varchar(256) DEFAULT NULL,
`authorities` varchar(256) DEFAULT NULL,
`access_token_validity` int(11) DEFAULT NULL,
`refresh_token_validity` int(11) DEFAULT NULL,
`additional_information` varchar(4096) DEFAULT NULL,
`autoapprove` varchar(256) DEFAULT NULL,
PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
----------
CREATE TABLE `oauth_refresh_token` (
`token_id` varchar(256) DEFAULT NULL,
`token` blob,
`authentication` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
第二步:IDEA+maven+springboot 集成OAuth2
这是服务器工程目录

1.pom中配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>OauthText</artifactId>
<groupId>OauthText</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion> <artifactId>OAuthService</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Spring Security Oauth2 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency> </dependencies> </project>
2.进行AuthorizationServerConfiguration.java 进行基本配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Autowired
private DataSource dataSource; @Bean // 声明TokenStore实现
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
} @Bean // 声明 ClientDetails实现
public ClientDetailsService clientDetails() {
return new JdbcClientDetailsService(dataSource);
} @Autowired
private TokenStore tokenStore; @Autowired
private AuthenticationManager authenticationManager; @Autowired
private UserService userService; @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.jdbc(dataSource);
} @Override // 配置框架应用上述实现
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
endpoints.tokenStore(tokenStore());
endpoints.userDetailsService(userService);
// 配置TokenServices参数
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(endpoints.getTokenStore());
tokenServices.setSupportRefreshToken(true);
tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
tokenServices.setAccessTokenValiditySeconds( (int) TimeUnit.DAYS.toSeconds(1)); // 1天
endpoints.tokenServices(tokenServices);
} @Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true); // support refresh token
tokenServices.setTokenStore(tokenStore); // use jdbc token store
return tokenServices;
}
3.ResourceServerConfiguration.java 进行配置
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").authenticated()
.anyRequest().authenticated();
} }
4.WebSecurityConfiguration.java 进行配置
@Configuration
public class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter { private final UserService userService; @Autowired
public WebSecurityConfiguration(UserService userService) {
this.userService = userService;
} @Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService); } }
5.进行自定义拦截配置
在service接口中

service 简单实现代码
@Service
public class UserServiceImpl implements UserService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("===================获取到token已进入自定义验证:"+username);
// 可以进行数据库请求,这里进行模拟
User user = new User();
user.setUsername("110");
user.setPassword("110119");
if (user == null) {
System.out.println("==================="+username);
throw new UsernameNotFoundException("Could not find the user '" + username + "'");
}
return new CustomUserDetails(user, true, true, true, true, null);
}
}
6.CustomUserDetails OAuth2 提供方法进行配置
public class CustomUserDetails extends User implements UserDetails {
private static final long serialVersionUID = 1702923242319850756L;
private final boolean enabled;
private final boolean accountNonExpired;
private final boolean credentialsNonExpired;
private final boolean accountNonLocked;
private final Set<GrantedAuthority> authorities;
public CustomUserDetails(User user, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
if (user != null
&& !StringUtils.isBlank(user.getUsername())
&& !StringUtils.isBlank(user.getPassword())) {
setUsername(user.getUsername());
setPassword(user.getPassword());
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
this.authorities = Collections.unmodifiableSet(new HashSet<>(CollectionUtils.emptyIfNull(authorities)));
} else {
throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}
@Override
public Set<GrantedAuthority> getAuthorities() {
return authorities;
}
}
这是Controller 配置只要访问log 就会被OAuth2 进行拦截验证
@RestController
@RequestMapping("/")
public class TextController { @PostMapping(value = "/log")
public String saveCuringEvidence(@RequestBody User user){
System.out.println("---------------------user:"+user.getUsername());
return user.getUsername();
} }
第三部:好了接下来进行postmain工具 模拟进行请求 url为你的域名+/oauth/token 获取token
1.首先配置客户端密码

2.而username和password 需要在刚刚建立的数据库进行自定义配置

3.模仿form表单进行配置

4.上面的账户和密码是自定义验证时需要的信息要和service里的账户和密码一致
成功之后
获取的access_token,复制下来

5.模仿客户端根据token请求数据

成功请求到数据 收工。。。。
OAuth2.0 配套客户端实现 :http://www.cnblogs.com/memoryXudy/p/7805217.html
源码:https://gitee.com/xdymemory00/Security-OAuth2-MiMaMoShi.git
Security-OAuth2.0 密码模式之服务端实现的更多相关文章
- oauth2.0密码模式详解
oauth2.0密码模式 欢迎关注博主公众号「Java大师」, 专注于分享Java领域干货文章http://www.javaman.cn/sb2/oauth-password 如果你高度信任某个应用, ...
- Spring Security OAuth2 Demo —— 密码模式(Password)
前情回顾 前几节分享了OAuth2的流程与授权码模式和隐式授权模式两种的Demo,我们了解到授权码模式是OAuth2四种模式流程最复杂模式,复杂程度由大至小:授权码模式 > 隐式授权模式 > ...
- IdentityServer4:IdentityServer4+API+Client+User实践OAuth2.0密码模式(2)
一.密码模式实操 仍然使用第一节的代码:做如下改动: 1.授权服务端 前面我们使用项目:Practice.IdentityServer作为授权服务器 修改项目的Config.cs类: 添加测试用户,并 ...
- webapi之owin的oauth2.0密码模式_01概述
一般在webapi接口中,为了防止接口被随意调用,都会验证用户身份. 然而不能每次调用接口都需要用户输入用户名密码来验证,这时就需要授权颁发令牌了,持有令牌就可以访问接口,接口也能验证令牌身份. 简单 ...
- springboot+spring security +oauth2.0 demo搭建(password模式)(认证授权端与资源服务端分离的形式)
项目security_simple(认证授权项目) 1.新建springboot项目 这儿选择springboot版本我选择的是2.0.6 点击finish后完成项目的创建 2.引入maven依赖 ...
- Spring Boot Security Oauth2之客户端模式及密码模式实现
Spring Boot Security Oauth2之客户端模式及密码模式实现 示例主要内容 1.多认证模式(密码模式.客户端模式) 2.token存到redis支持 3.资源保护 4.密码模式用户 ...
- Spring Security OAuth2.0认证授权二:搭建资源服务
在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...
- 基于spring boot2.0+spring security +oauth2.0+ jwt微服务架构
github地址:https://github.com/hankuikuide/microservice-spring-security-oauth2 项目介绍 该项目是一个演示项目,主要演示了,基于 ...
- Spring Cloud Security OAuth2.0 认证授权系列(一) 基础概念
世界上最快的捷径,就是脚踏实地,本文已收录[架构技术专栏]关注这个喜欢分享的地方. 前序 最近想搞下基于Spring Cloud的认证授权平台,总体想法是可以对服务间授权,想做一个基于Agent 的无 ...
随机推荐
- shell编程变量赋值
[shell编程变量赋值] 1.等号两边均不能有空格存在.例, a="hello world" 2.变量和其它文字以{}或空格格开,否则会混淆.例, 有时候变量名可能会和其它文 ...
- java 数字金额转换中文金额
public static String digitUppercase(double n){ String fraction[] = {"角", "分"}; S ...
- Eclipse下生成.dll动态库及.a静态库使用 for Windows [z]
以后的主要工作就是做库了,将我们的C或者C++写的接口做成库,给客户端使用,因此有必要知道库的使用和制作方法.主要是在Eclipse下搞了搞,公司用的是Carbide,也差不多.库做好了,用SVN已提 ...
- DART: a fast and accurate RNA-seq mapper with a partitioning strategy DART:使用分区策略的快速准确的RNA-seq映射器
DART: a fast and accurate RNA-seq mapper with a partitioning strategyDART:使用分区策略的快速准确的RNA-seq映射器 Abs ...
- DIV+CSS布局时, DIV的高度和宽度特性
这个没有特别的做要求,你要根据你自己的页面整体布局来设置,还有根据div的特性来设置,div默认情况是宽度最大化(100%).高度最小化,高度随着内容自动伸展: 一般情况做网页的话,大部分都是固定了总 ...
- Python中where()函数的用法
where()的用法 首先强调一下,where()函数对于不同的输入,返回的只是不同的. 1当数组是一维数组时,返回的值是一维的索引,所以只有一组索引数组 2当数组是二维数组时,满足条件的数组值返回的 ...
- 服务器上如何再另外添加一个E盘
我的电脑按右键,选择管理..然后在左边选择磁盘管理,然后对着C盘或者D盘按右键,选择压缩卷,等一下下,就会出现个框框让你选择压缩多少,然后多了一个可用空间,再把它分成一个分区就OK拉 步骤:对可用空间 ...
- Hadoop中Writable类之二
1.ASCII.Unicode.UFT-8 在看Text类型的时候,里面出现了上面三种编码,先看看这三种编码: ASCII是基于拉丁字母的一套电脑编码系统.它主要用于显示现代英语和其他西欧语言.它是现 ...
- Fork/Join 型线程池与 Work-Stealing 算法
JDK 1.7 时,标准类库添加了 ForkJoinPool,作为对 Fork/Join 型线程池的实现.Fork 在英文中有 分叉 的意思,而 Join 有 合并 的意思.ForkJoinPool ...
- scala中Nil用法
http://www.runoob.com/scala/scala-lists.html 即Nil是空List 双冒号是追加进入 package com.yjsj.spark object scala ...