一:授权服务器相关代码

AuthorizationServer.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; import javax.sql.DataSource; @Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource; @Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
} @Bean
public ClientDetailsService clientDetails() {
return new JdbcClientDetailsService(dataSource);
} @Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()");
} @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetails());
} @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore());
}
}
WebSecurityConfig.java
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder; @Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
} @SuppressWarnings("deprecation")
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
单独放开一些权限,还需加上
 @Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers(HttpMethod.OPTIONS, "/oauth/token", "/rest/**", "/api/**", "/**")
.and()
.csrf().disable();
}
Application.java
import java.security.Principal;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@EnableResourceServer
@SpringBootApplication
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} @RequestMapping("/validateUser")
public Principal user(Principal user) {
return user;
}
}

application.yml

server:
port: 94 spring:
datasource:
url: jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521/orcl
username: xxx
password: xxx
driver-class-name: oracle.jdbc.driver.OracleDriver

pom.xml

<?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">
<modelVersion>4.0.0</modelVersion> <groupId>com.javainuse</groupId>
<artifactId>boot-oauth2-authorization-server</artifactId>
<version>0.0.1.SNAPSHOT</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.jslsolucoes</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.1.0</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

二:资源服务器

TestController.java
@RestController
public class TestController { @RequestMapping("/test")
public String test() {
return "Hello World";
}
}
 Application.java
@RestController
@EnableResourceServer
@SpringBootApplication
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

application.yml

security:
oauth2:
resource:
userInfoUri: http://localhost:94/validateUser
server:
port: 9090

pom.xml

<?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">
<modelVersion>4.0.0</modelVersion> <groupId>com.javainuse</groupId>
<artifactId>winway-oauth2-resource-server</artifactId>
<version>0.0.1.SNAPSHOT</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

三:测试

1,获取token

2, 验证token

localhost:94/oauth/check_token?token=ebc3412f-9e40-4cd3-a5f3-b1587a6700fa

四:数据库脚本

https://github.com/Abdullah8006/jdbctokenstore_schema_oracle/blob/master/jdbctokenstore_oracle_schema.sql

-- used in tests that use HSQL
create table oauth_client_details (
client_id VARCHAR(256) PRIMARY KEY,
resource_ids VARCHAR(256),
client_secret VARCHAR(256),
scope VARCHAR(256),
authorized_grant_types VARCHAR(256),
web_server_redirect_uri VARCHAR(256),
authorities VARCHAR(256),
access_token_validity INTEGER,
refresh_token_validity INTEGER,
additional_information VARCHAR(256),
autoapprove VARCHAR(256)
); create table oauth_client_token (
token_id VARCHAR(256),
token BLOB,
authentication_id VARCHAR(256) PRIMARY KEY,
user_name VARCHAR(256),
client_id VARCHAR(256)
); create table oauth_access_token (
token_id VARCHAR(256),
token BLOB,
authentication_id VARCHAR(256) PRIMARY KEY,
user_name VARCHAR(256),
client_id VARCHAR(256),
authentication BLOB,
refresh_token VARCHAR(256)
); create table oauth_refresh_token (
token_id VARCHAR(256),
token BLOB,
authentication BLOB
); create table oauth_code (
code VARCHAR(256), authentication BLOB
); create table oauth_approvals (
userId VARCHAR(256),
clientId VARCHAR(256),
scope VARCHAR(256),
status VARCHAR(10),
expiresAt TIMESTAMP,
lastModifiedAt TIMESTAMP
); -- customized oauth_client_details table
create table ClientDetails (
appId VARCHAR(256) PRIMARY KEY,
resourceIds VARCHAR(256),
appSecret VARCHAR(256),
scope VARCHAR(256),
grantTypes VARCHAR(256),
redirectUrl VARCHAR(256),
authorities VARCHAR(256),
access_token_validity INTEGER,
refresh_token_validity INTEGER,
additionalInformation VARCHAR(256),
autoApproveScopes VARCHAR(256)
);

五:后续

把Spring Boot从1.n升级到2.n时,运行上面示例一直报错误的token。
   需要引入下面jar包

<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>

理论上不引入上面jar包,根据 https://docs.spring.io/spring-boot/docs/2.0.0.M7/reference/htmlsingle/#_client也可以配置成功,有待继续研究。

六: 跨域问题解决

如果想在js中能获取到token,还需要加两个文件

CommonInterceptor.java
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
拦截器主要用来放行Option请求验证
*/ public class CommonInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Authorization"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} return true;
} public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
} public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
CorsFilter.java
import org.springframework.core.annotation.Order;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 跨域参数设置拦截器
*/ @Order(1)
@WebFilter(filterName = "corsFilter", urlPatterns = "/*")
public class CorsFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN"); chain.doFilter(req, response);
} public void init(FilterConfig config) throws ServletException
{
} public void destroy() {
}
}

Application再加上

@ServletComponentScan               //扫描filter
 

参考资料

https://github.com/FrontierPsychiatrist/spring-oauth-example

初步理解Spring Security并实践
  https://www.jianshu.com/p/e6655328b211

spring security之httpSecurity使用示例
  http://www.cnblogs.com/davidwang456/p/4549344.html

spring-oauth-server 数据库表说明

https://blog.csdn.net/u011676300/article/details/84390988#oauth_access_token_33

官方示例:https://spring.io/guides/tutorials/spring-boot-oauth2/

详细配置:https://docs.spring.io/spring-boot/docs/2.0.0.M7/reference/htmlsingle/#_client

OAuth2.0配置的更多相关文章

  1. SpringBoot之oauth2.0学习之服务端配置快速上手

    现在第三方登录的例子数见不鲜.其实在这种示例当中,oauth2.0是使用比较多的一种授权登录的标准.oauth2.0也是从oauth1.0升级过来的.那么关于oauth2.0相关的概念及其原理,大家可 ...

  2. Spring security + oauth2.0 + redis + mybatis plus 搭建微服务

    上个星期一个朋友请求帮忙,让我搭建一个分布式授权中心的微服务,之前我也没搭建过,在网上撸了几天前辈们写的技术博客,搞出个模型,分享给大家: 前辈们博客地址: OAuth2.0 原理:https://b ...

  3. Spring Boot 集成 Swagger2 与配置 OAuth2.0 授权

    Spring Boot 集成 Swagger2 很简单,由于接口采用了OAuth2.0 & JWT 协议做了安全验证,使用过程中也遇到了很多小的问题,多次尝试下述配置可以正常使用. Maven ...

  4. Spring Cloud OAuth2.0 微服务中配置 Jwt Token 签名/验证

    关于 Jwt Token 的签名与安全性前面已经做了几篇介绍,在 IdentityServer4 中定义了 Jwt Token 与 Reference Token 两种验证方式(https://www ...

  5. SpringBootSecurity学习(16)前后端分离版之 OAuth2.0 加密配置

    示例代码的改进 前面使用spring cloud security和spring cloud oauth2写了一个第三方授权的例子,例子非常的简单,主要目的是用来熟悉OAuth2.0 申请授权的整个流 ...

  6. JMeter配置Oauth2.0授权接口访问

    本文主要介绍如何使用JMeter配置客户端凭证(client credentials)模式下的请求 OAuth2.0介绍 OAuth 2.0 是一种授权机制,主要用来颁发令牌(token) 客户端凭证 ...

  7. SimpleSSO:使用Microsoft.Owin.Security.OAuth搭建OAuth2.0授权服务端

    目录 前言 OAuth2.0简介 授权模式 (SimpleSSO示例) 使用Microsoft.Owin.Security.SimpleSSO模拟OpenID认证 通过authorization co ...

  8. 分享一个单点登录、OAuth2.0授权系统源码(SimpleSSO)

    SimpleSSO 关于OAuth 2.0介绍: http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html 系统效果: 登录界面: 首页: 应用界面: ...

  9. 【OAuth2.0】Spring Security OAuth2.0篇之初识

    不吐不快 因为项目需求开始接触OAuth2.0授权协议.断断续续接触了有两周左右的时间.不得不吐槽的,依然是自己的学习习惯问题,总是着急想了解一切,习惯性地钻牛角尖去理解小的细节,而不是从宏观上去掌握 ...

随机推荐

  1. python flask_Sqlalchemy管理数据库

    懒癌复发直接粘贴代码,算是做一个简单备份吧. #coding:utf8 from flask import Flask from flask_sqlalchemy import SQLAlchemy ...

  2. Python中os与sys两模块的区别

    <os和sys的官方解释> ➤os os: This module provides a portable way of using operating system dependent ...

  3. 2017-10-22—光电二极管

    光通信基本每天都会接触光电二极管,光模块说简单点就是电光转换和光电转换. 光传输模块在整体产品架构上则包括光学次模块(Optical Subassembly;OSA)及电子次模块(Electrical ...

  4. python3类方法与静态方法

    静态⽅法和类⽅法 转载于:https://blog.csdn.net/qq_41020281/article/details/79634707 1. 类⽅法 是类对象所拥有的⽅法,需要⽤修饰器 @cl ...

  5. (88)Wangdao.com第二十一天_JavaScript 元素节点Element 节点

    Element 节点 (元素节点) 是一组对象 对应网页的 HTML 元素 每一个 HTML 元素,在 DOM 树上都会转化成一个 Element 节点对象(以下简称元素节点) 所有元素节点的 nod ...

  6. 3.2station

    题意火车进入,然后要求以最大字典序输出 解题思路:先用一个数组储存当前位置之后最大的数字是什么,然后把已经进站的最后一节火车和还没进站的车的最大值,哪个更大,如果已经进站的更大,那么就先出站,否则就先 ...

  7. [LeetCode] Champagne Tower 香槟塔

    We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so ...

  8. [LeetCode] Split BST 分割二叉搜索树

    Given a Binary Search Tree (BST) with root node root, and a target value V, split the tree into two ...

  9. 将整数m的各位数字保存到数组A中

    import java.util.Scanner; /** * @author:(LiberHome) * @date:Created in 2019/3/4 20:10 * @description ...

  10. python语法_嵌套

    列表里面每个元素可以是不同的数据类型,每一个元素也可以是一个列表或者元组等, a = [[1,2,3],"a",13,(5,7,9,"dasd")] b = a ...