spring security oauth2.0 实现
oauth应该属于security的一部分。关于oauth的的相关知识可以查看阮一峰的文章:http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html
一、目标
现在很多系统都支持第三方账号密码等登陆我们自己的系统,例如:我们经常会看到,一些系统使用微信账号,微博账号、QQ账号等登陆自己的系统,我们现在就是要模拟这种登陆的方式,很多大的公司已经实现了这种授权登陆的方式,并提供了相应的API,供我们开发人员调用。他们实际上用的也规范是oauth2.0的规范,通过用户授权的方式,获取一些信息。以前就做过一些类似的,如:
微信扫码登陆:http://www.cnblogs.com/0201zcr/p/5133062.html
微信客户端授权登陆:http://www.cnblogs.com/0201zcr/p/5131602.html
但是假如你的系统要提供其他网站使用你的账号密码登陆,你就需要写好相应的接口规范, 给人家调用。用得比较多的是使用spring security oauth实现的方式。
我们这里使用meaven导入我们所需要的jar包,使用配置文件的方式拦截我们的请求并进行验证是否有效,然后即可获取我们需要的信息。
这里主要是模拟了通过给予第三方账号密码的方式,在第三方进行鉴权,然后将access_token等信息传回过来,然后要登录的系统在通过这个返回的access_token去第三方请求一些用户授权的数据。即可完成第三方的账号密码登录。
二、Spring security oauth 相关依赖meaven配置
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.zhangfc</groupId>
<artifactId>demo4ssh-security-oauth2</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version> <properties>
<spring.version>4.0.4.RELEASE</spring.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<spring-security.version>3.2.4.RELEASE</spring-security.version>
<spring-security-oauth2.version>2.0.2.RELEASE</spring-security-oauth2.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${spring-security-oauth2.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>tomcat</groupId>
<artifactId>servlet-api</artifactId>
<version>5.5.23</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>tomcat</groupId>
<artifactId>jsp-api</artifactId>
<version>5.5.23</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.2.Final</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies> <build>
<finalName>demo4ssh-security-oauth2</finalName>
</build>
</project>
三、web.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true" version="3.0"> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/META-INF/infrastructure.xml,classpath*:/META-INF/applicationContext*.xml</param-value>
</context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>
四、applicationContext-security.xml
oauth2是security的一部分,配置也有关联,就不再单建文件
添加http拦截链
<!-- /oauth/token 是oauth2登陆验证请求的url 用于获取access_token ,默认的生存时间是43200秒,即12小时-->
<http pattern="/oauth/token" create-session="stateless"
authentication-manager-ref="oauth2AuthenticationManager">
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" /> <!-- 可以访问的角色名称,如果需要拦截,需要实现UserDetails接口,实现getAuthorities()方法-->
<anonymous enabled="false" />
<http-basic entry-point-ref="oauth2AuthenticationEntryPoint" />
<custom-filter ref="clientCredentialsTokenEndpointFilter"
before="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauth2AccessDeniedHandler" />
</http>
这个标签处理/oauth/token的网络请求,这是oauth2的登录验证请求,那么登录需要什么,首先,和Spring Security一样,需要一个认证管理器,Spring Oauth2需要两个认证管理器,第一个就是之前Spring中配置的那一个,用来验证用户名密码的,
<!-- 验证的权限控制 -->
<authentication-manager>
<authentication-provider>
<!-- <password-encoder hash="md5"> <salt-source user-property="email"/>
</password-encoder> -->
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select username, password, 1 from user where username = ?"
authorities-by-username-query="select u.username, r.role from user u left join role r on u.role_id=r.id where username = ?" />
</authentication-provider>
</authentication-manager>
还有一个是用来区分客户端用户的,给它起个名字叫oauth2AuthenticationManager:
<oauth2:client-details-service id="clientDetailsService" >
<oauth2:client client-id="mobile_1"
authorized-grant-types="password,authorization_code,refresh_token,implicit"
secret="secret_1" scope="read,write,trust" />
</oauth2:client-details-service>
<beans:bean id="oauth2ClientDetailsUserService"
class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<beans:constructor-arg ref="clientDetailsService" />
</beans:bean>
<authentication-manager id="oauth2AuthenticationManager">
<authentication-provider user-service-ref="oauth2ClientDetailsUserService" />
</authentication-manager>
这儿设置了一种客户端,id叫做mobile_1,secret叫做secret_1,针对read、write和trust几个域有效。这几个域会在访问控制中被用到。
当登录成功之后会得到一个token,再次访问的时候需要携带这个token,spring-oauth2根据这个token来做认证,那么spring-oauth2必须先存一份token和用户关系的对应,因为不用session了,这就相当于session,那么这个token在服务器中怎么存,有两种主要的存储方式,一是创建数据表,把token存到数据库里,我现在追求简单可用,采用第二种方式,直接存到内存里。下面配置一个管理token的service:
<!-- for spring oauth2 -->
<!--token在服务器存储的方式 InMemoryTokenStore :保存在内存 ;JdbcTokenStore : 保存在数据库中 -->
<beans:bean id="tokenStore"
class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore" />
<!--<beans:bean id="tokenServices"
class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">--> <!--令牌服务的实体-->
<beans:bean id="tokenServices"
class="org.zhangfc.demo4ssh.service.MyTokenService"> <!-- 自己重写的类 -->
下面配置4个基本的bean:分别处理访问成功、访问拒绝、认证点和访问控制:
<!--处理访问成功-->
<beans:bean id="oauth2AuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint" />
<!--处理访问拒绝-->
<beans:bean id="oauth2AccessDeniedHandler"
class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<!--处理认证点-->
<beans:bean id="oauthUserApprovalHandler"
class="org.springframework.security.oauth2.provider.approval.DefaultUserApprovalHandler" />
<!--处理访问控制-->
<beans:bean id="oauth2AccessDecisionManager"
class="org.springframework.security.access.vote.UnanimousBased">
<beans:constructor-arg>
<beans:list>
<beans:bean
class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
<beans:bean class="org.springframework.security.access.vote.RoleVoter" />
<beans:bean
class="org.springframework.security.access.vote.AuthenticatedVoter" />
</beans:list>
</beans:constructor-arg>
</beans:bean>
配置这个oauth2的server所能支持的请求类型:
<!--oauth2 的server所能支持的请求类型-->
<oauth2:authorization-server
client-details-service-ref="clientDetailsService" token-services-ref="tokenServices"
user-approval-handler-ref="oauthUserApprovalHandler">
<oauth2:authorization-code />
<oauth2:implicit />
<oauth2:refresh-token />
<oauth2:client-credentials />
<oauth2:password />
</oauth2:authorization-server>
我们的请求里,要把验证类型、用户名密码都作为表单参数提交,这就需要配置下面的filter:
<beans:bean id="clientCredentialsTokenEndpointFilter"
class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<beans:property name="authenticationManager" ref="oauth2AuthenticationManager" />
</beans:bean>
下面定义一种资源,指定spring要保护的资源,如果没有这个,访问控制的时候会说没有Authentication object:
<!--指定spring要保护的资源,如果没有这个,访问控制的时候会说没有Authentication object:-->
<oauth2:resource-server id="mobileResourceServer"
resource-id="mobile-resource" token-services-ref="tokenServices" />
好了,到此为止基本配置就都有了,下面就看访问控制的配置:在前面的拦截链上,已经为登录验证配了一个/auth/token,在这个标签下面添加对/json和/admin这两个路径的控制
<http pattern="/json**" create-session="never"
entry-point-ref="oauth2AuthenticationEntryPoint"
access-decision-manager-ref="oauth2AccessDecisionManager">
<anonymous enabled="false" />
<intercept-url pattern="/json**" access="ROLE_USER" />
<custom-filter ref="mobileResourceServer" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauth2AccessDeniedHandler" />
</http>
<http pattern="/admin**" create-session="never"
entry-point-ref="oauth2AuthenticationEntryPoint"
access-decision-manager-ref="oauth2AccessDecisionManager">
<anonymous enabled="false" />
<intercept-url pattern="/admin**" access="SCOPE_READ,ROLE_ADMIN" />
<custom-filter ref="mobileResourceServer" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauth2AccessDeniedHandler" />
</http>
我们用oauth2AccessDecisionManager来做决策,这个地方需要注意,spring-security里面配置access="ROLE_USER,ROLE_ADMIN"是说user和admin都可以访问,是一个“或”的关系,但是这里是“与”的关系,比如第二个,需要ROLE_ADMIN并且当前的scope包含read才可以,否则就没有权限。认证失败会返回一段xml,这个可以自定义handler来修改,暂且按下不表。
默认的12小时access_token可能对于我们来说太长,通过UUID.randomUUID()来生成一个36的唯一的access_token 也不是我们想要的生存方式。故我们可以复制org.springframework.security.oauth2.provider.token.DefaultTokenServices,并对其进行一定修改即可,这里我把这个类复制出来,修改成MyTokenService,并在上面的配置文件中进行了配置。主要是修改其以下成员变量:
private int refreshTokenValiditySeconds = 2592000; //refresh_token 的超时时间 默认2592000秒
private int accessTokenValiditySeconds = 10; //access_token 的超时时间 默认12个小时
private boolean supportRefreshToken = false; //是否支持access_token 刷新,默认是false,在配置文件中以配置成可以支持了,
private boolean reuseRefreshToken = true; //使用refresh_token刷新之后该refresh_token是否依然使用,默认是依然使用
private TokenStore tokenStore; //access_token的存储方式,这个在配置文件中配
通过修改修改其createAccessToken方法来修改access_token 的生成方式:
private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
String access_tokens = UUID.randomUUID().toString().replaceAll("-","");
DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(access_tokens);
int validitySeconds = this.getAccessTokenValiditySeconds(authentication.getOAuth2Request());if(validitySeconds > 0) {
token.setExpiration(new Date(System.currentTimeMillis() + (long)validitySeconds * 1000L)); token.setRefreshToken(refreshToken);
token.setScope(authentication.getOAuth2Request().getScope());
return (OAuth2AccessToken)(this.accessTokenEnhancer != null?this.accessTokenEnhancer.enhance(token, authentication):token);
}
源码下载:http://pan.baidu.com/s/1mhSfKFY
获取access_token URL :
http://localhost:8080/AOuth/oauth/token?client_id=mobile_1&client_secret=secret_1&grant_type=password&username=aa&password=aa
这时候会返回一个access_token:
{"access_token":"4219a91f-45d5-4a07-9e8e-3acbadd0c23e","token_type":"bearer","refresh_token":"d41df9fd-3d36-4a20-b0b7-1a1883c7439d","expires_in":43199,"scope":"read write trust"}
这之后再拿着这个access_token去访问资源:
http://localhost:8080/AOuth/admin?access_token=4219a91f-45d5-4a07-9e8e-3acbadd0c23e
刷新access_token:
http://localhost:8080/AOuth/oauth/token?client_id=mobile_1&client_secret=secret_1&grant_type=refresh_token&refresh_token=ad18fc89e1424278b675ca05bf8afbb3
致谢:感谢您的阅读!
spring security oauth2.0 实现的更多相关文章
- 【OAuth2.0】Spring Security OAuth2.0篇之初识
不吐不快 因为项目需求开始接触OAuth2.0授权协议.断断续续接触了有两周左右的时间.不得不吐槽的,依然是自己的学习习惯问题,总是着急想了解一切,习惯性地钻牛角尖去理解小的细节,而不是从宏观上去掌握 ...
- springboot+spring security +oauth2.0 demo搭建(password模式)(认证授权端与资源服务端分离的形式)
项目security_simple(认证授权项目) 1.新建springboot项目 这儿选择springboot版本我选择的是2.0.6 点击finish后完成项目的创建 2.引入maven依赖 ...
- Spring Security OAuth2.0 - AuthorizationServer和ResourceServer分离
<Spring Security实现OAuth2.0授权服务 - 基础版>和<Spring Security实现OAuth2.0授权服务 - 进阶版>两篇文章中介绍如何搭建OA ...
- 基于spring boot2.0+spring security +oauth2.0+ jwt微服务架构
github地址:https://github.com/hankuikuide/microservice-spring-security-oauth2 项目介绍 该项目是一个演示项目,主要演示了,基于 ...
- Spring Security OAuth2.0认证授权二:搭建资源服务
在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...
- Spring Security OAuth2.0认证授权三:使用JWT令牌
Spring Security OAuth2.0系列文章: Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二: ...
- Spring Security OAuth2.0认证授权四:分布式系统认证授权
Spring Security OAuth2.0认证授权系列文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授 ...
- Spring Security OAuth2.0认证授权五:用户信息扩展到jwt
历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...
- Spring Security OAuth2.0认证授权六:前后端分离下的登录授权
历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...
随机推荐
- effective java 读后感
think in java , effective java 这两本书一直都在java的生态圈中经久不衰.本来想着先翻过 think in java 这本大山,但是读到一半就放弃了.过长的篇幅,让 ...
- 用Javascript模拟微信飞机大战游戏
最近微信的飞机大战非常流行,下载量非常高. 利用JS进行模拟制作了一个简单的飞机大战[此源码有很多地方可以进行重构和优化] [此游戏中没有使用HTML5 任何浏览器都可以运行]. 效果图: 原理:利用 ...
- 获取documents、tmp、app、Library的路径的方法
phone沙箱模型的有四个文件夹: documents,tmp,app,Library 1.Documents 您应该将所有的应用程序数据文件写入到这个目录下.这个目录用于存储用户数据或其它 ...
- MVC5+EF6+AutoMapper+Bootstrap打造在线博客(1.0)
目的:MVC5+EF6开发一个高并发.分布式的在线博客,等开发完成以后再用.net core,mysql重新开发,部署到linux系统上,这一系列就算完结,经验不足,大家一起讨论进步,源代码下载QQ群 ...
- 高效的SQLSERVER分页查询的几种示例分析
Sqlserver数据库分页查询一直是Sqlserver的短板,闲来无事,想出几种方法,假设有表ARTICLE,字段ID.YEAR...(其他省略),数据53210条(客户真实数据,量不大),分页查询 ...
- Android使用ViewPager实现左右循环滑动及轮播效果
边界的时候会看到一个不能翻页的动画,可能影响用户体验.此外,某些区域性的ViewPager(例如展示广告或者公告之类的ViewPager),可能需要自动轮播的效果,即用户在不用滑动的情况下就能够看到其 ...
- Jar mismatch错误的解决
新建了一个项目,包含了两个库:appcompat_v7和swipelistview,结果出现了Jar mismatch错误: [2016-04-11 17:17:27 - MySwipeListVie ...
- 数据结构:顺序表(python版)
顺序表python版的实现(部分功能未实现) #!/usr/bin/env python # -*- coding:utf-8 -*- class SeqList(object): def __ini ...
- 华硕笔记本U盘启动系统/WinPE报错。Windows failed to start. A Recent hardware or software change might be the cause.
最近在整一台华硕笔记本,大概有5年寿命了吧,质量还行,由于系统出了问题,打算用自制U盘WinPE进去修复一下.按照个人经验,在主板设置里启用了USB启动选项,并且设置USB启动顺序为第一个,可是进系统 ...
- 关于XAMPP默认端口80 和443被占用的问题
关于安装xampp-win32-1.8.1-VC9-installer.zip后启动时候报端口80和443被占用的问题解决 xampp-win32-1.8.1-VC9-installer.zip下载地 ...