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.0modelVersion> <groupId>org.zhangfcgroupId> <artifactId>demo4ssh-security-oauth2artifactId> <packaging>warpackaging> <version>0.0.1-SNAPSHOTversion> <properties> <spring.version>4.0.4.RELEASEspring.version> <hibernate.version>4.3.5.Finalhibernate.version> <spring-security.version>3.2.4.RELEASEspring-security.version> <spring-security-oauth2.version>2.0.2.RELEASEspring-security-oauth2.version> properties> <dependencies> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-ormartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframework.securitygroupId> <artifactId>spring-security-configartifactId> <version>${spring-security.version}version> dependency> <dependency> <groupId>org.springframework.securitygroupId> <artifactId>spring-security-taglibsartifactId> <version>${spring-security.version}version> dependency> <dependency> <groupId>org.springframework.security.oauthgroupId> <artifactId>spring-security-oauth2artifactId> <version>${spring-security-oauth2.version}version> dependency> <dependency> <groupId>org.hibernategroupId> <artifactId>hibernate-coreartifactId> <version>${hibernate.version}version> dependency> <dependency> <groupId>javax.servlet.jsp.jstlgroupId> <artifactId>javax.servlet.jsp.jstl-apiartifactId> <version>1.2.1version> dependency> <dependency> <groupId>taglibsgroupId> <artifactId>standardartifactId> <version>1.1.2version> dependency> <dependency> <groupId>tomcatgroupId> <artifactId>servlet-apiartifactId> <version>5.5.23version> <scope>providedscope> dependency> <dependency> <groupId>tomcatgroupId> <artifactId>jsp-apiartifactId> <version>5.5.23version> <scope>providedscope> dependency> <dependency> <groupId>commons-fileuploadgroupId> <artifactId>commons-fileuploadartifactId> <version>1.3.1version> dependency> <dependency> <groupId>org.hibernategroupId> <artifactId>hibernate-validatorartifactId> <version>5.1.2.Finalversion> dependency> <dependency> <groupId>c3p0groupId> <artifactId>c3p0artifactId> <version>0.9.1.2version> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>5.1.31version> dependency> <dependency> <groupId>org.codehaus.jacksongroupId> <artifactId>jackson-mapper-aslartifactId> <version>1.9.13version> dependency> dependencies> <build> <finalName>demo4ssh-security-oauth2finalName> 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>contextConfigLocationparam-name>
<param-value>
classpath:/META-INF/infrastructure.xml,classpath*:/META-INF/applicationContext*.xmlparam-value>
context-param>
<listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>spring-dispatcherservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>spring-dispatcherservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>springSecurityFilterChainfilter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
filter>
<filter-mapping>
<filter-name>springSecurityFilterChainfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
四、applicationContext-security.xml
oauth2是security的一部分,配置也有关联,就不再单建文件
添加http拦截链
"/oauth/token" create-session="stateless" authentication-manager-ref="oauth2AuthenticationManager"> "/oauth/token" access="IS_AUTHENTICATED_FULLY" /> "false" /> ref="oauth2AuthenticationEntryPoint" /> ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" /> ref="oauth2AccessDeniedHandler" />
这个标签处理/oauth/token的网络请求,这是oauth2的登录验证请求,那么登录需要什么,首先,和Spring Security一样,需要一个认证管理器,Spring Oauth2需要两个认证管理器,第一个就是之前Spring中配置的那一个,用来验证用户名密码的,
<authentication-manager> <authentication-provider> <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:
<beans:bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore" /> <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: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:
<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
致谢:感谢您的阅读!