Spring Security oauth2.0 Implementation

Source: Internet
Author: User
Tags oauth

OAuth should be part of security. For more information about OAuth, you can view Nanyi's article: http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

First, the goal

Now many systems support third-party account password and so on to our own system, such as: we often see, some systems use account, Weibo account, QQ account and other landing their own system, we are now to simulate this way of landing, a lot of large companies have achieved this kind of authorization landing way, and provide the appropriate APIs for our developers to call. They actually use the norm is the oauth2.0 specification, through the user authorization way, obtains some information. have done something similar before, such as:

Scan Code Login:http://www.cnblogs.com/0201zcr/p/5133062.html

Client Authorized Login: http://www.cnblogs.com/0201zcr/p/5131602.html

But if your system is going to provide other websites to use your account password to log in, you need to write the appropriate interface specification, to call someone else. The use of the spring security OAuth implementation is much more.

We use Meaven to import the jar packages we need, use the configuration file to intercept our requests and verify that they are valid, and then get the information we need.

This is mainly simulated by giving a third party account password, the third party authentication, and then the Access_token and other information back, and then to log on the system in the return of the Access_token to third parties to request some user authorization data. You can complete a third-party account password login.

Two, Spring security OAuth dependent Meaven configuration

<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> 

Iii. Web. xml file Configuration

<?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/i Nfrastructure.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> <filt Er-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>

Iv. Applicationcontext-security.xml

Oauth2 is part of security, configuration is also associated, no more single-build files

Add an HTTP intercept chain

    <!--  /oauth/token is the URL for oauth2 login authentication request     to get Access_token  , the default lifetime is 43,200 seconds, which is 12 hour    -to 

This tag handles/oauth/token's network request, which is Oauth2 's login authentication request, so what is required for login, first, like spring security, requires an authentication manager, Spring OAUTH2 requires two authentication manager, The first is the one that was configured in spring to verify the user name password,

    <!--authentication rights control-    <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 the user U left join role R on U.role_id=r.id where username =? "/>        </authentication-provider>    </authentication-manager>

Another is to distinguish the client user, give it a name called 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>

Here a client is set up, called Mobile_1,secret, called secret_1, which is valid for read, write, and trust several domains. These domains are used in access control.

When the login is successful, you will get a token and you will need to carry this token,spring-oauth2 according to this token to authenticate, then spring-oauth2 must save a token and the user relations correspondence, Because there is no session, this is equivalent to the session, then this token in the server How to save, there are two main storage methods, one is to create a data table, the token into the database , I now pursue simple, using the second way, Stored directly in the memory . Configure a service to manage tokens below:

    <!--for spring oauth2    --<!--token inmemorytokenstore in the way the server is stored    : memory is present     ; Jdbctokenstore: Save in database--    <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" >-->     <!--Token Service entity--    <beans:bean id= "tokenservices"                class= " Org.zhangfc.demo4ssh.service.MyTokenService ">      <!--self-overriding class--

Here are 4 basic beans: Handling access success, Access denied, authentication points, and access control, respectively:

    <!--processing Access success-<beans:bean id= "Oauth2authenticationentrypoint" class= "org.springframework.security.o Auth2.provider.error.OAuth2AuthenticationEntryPoint "/> <!--handling Access Denied--<beans:bean id=" Oauth2accessdeniedhandler "class=" Org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler " /> <!--Processing certification points--<beans:bean id= "Oauthuserapprovalhandler" class= "Org.springframework.security.oau Th2.provider.approval.DefaultUserApprovalHandler "/> <!--handling access Control--<beans:bean id=" Oauth2accessdecisionmanager "class=" org.springframework.security.access.vote.UnanimousBased "> <beans:c onstructor-arg> <beans:list> <beans:bean class= "Org.springframewo Rk.security.oauth2.provider.vote.ScopeVoter "/> <beans:bean class=" org.springframework.security.acces             S.vote.rolevoter "/> <beans:bean       class= "Org.springframework.security.access.vote.AuthenticatedVoter"/> </beans:list> &lt ;/beans:constructor-arg> </beans:bean>

Configure the type of requests that this OAUTH2 server can support:

    <!--OAUTH2 Server can support request types--    <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>

In our request, to submit the authentication type and user name password as form parameters, you need to configure the following filter:

    <beans:bean id= "Clientcredentialstokenendpointfilter"        class= " Org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter ">        <beans: Property Name= "AuthenticationManager" ref= "Oauth2authenticationmanager"/>    </beans:bean>

The following defines a resource that specifies the resources that spring wants to protect, without which the access control will say no Authentication object:

    <!--Specify the resources that spring wants to protect, and without this, the access control will say no authentication object:-->    <oauth2:resource-server id= " Mobileresourceserver "        resource-id=" Mobile-resource "token-services-ref=" Tokenservices "/>

All right, here's the basic configuration, here's the configuration for the access control: on the previous intercept chain, a/AUTH/TOKEN has been configured for login verification, and the two paths of/json and/admin are added under this tag.

    

We use Oauth2accessdecisionmanager to make decisions, this place needs to be noted, spring-security inside the configuration access= "Role_user,role_admin" is said that both USER and ADMIN can access, is a "or" relationship, but here is the "with" relationship, such as the second one, requires role_admin and the current scope contains read only, otherwise there is no permission. Authentication failure will return an XML, this can be customized handler to modify, for the moment, do not press the table.

The default 12-hour Access_token may be too long for us to generate a 36 unique Access_token through UUID.RANDOMUUID () and not the way we want to live. So we can copy org.springframework.security.oauth2.provider.token.DefaultTokenServices, and make certain changes to it, here I copied this class, modified into Mytokenservice, And configured in the configuration file above. The main change is to modify the following member variables:

    private int refreshtokenvalidityseconds = 2592000;       Refresh_token Timeout time  default 2.592 million seconds    private int accesstokenvalidityseconds = ten;             Access_token Timeout time   default 12 hours    Private Boolean supportrefreshtoken = false;            Whether Access_token refresh is supported, the default is False, in the configuration file to be configured to support,    private Boolean reuserefreshtoken = true;               Use Refresh_token Refresh after the Refresh_token is still used, the default is to still use the    private Tokenstore tokenstore;                             Access_token is stored in a configuration file with the

Modify how the Access_token is generated by modifying its Createaccesstoken method:

    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);    }

SOURCE Download: Http://pan.baidu.com/s/1mhSfKFY

Get Access_token URL:

Http://localhost:8080/AOuth/oauth/token?client_id=mobile_1&client_secret=secret_1&grant_type=password &username=aa&password=aa

This will return a 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 "}

And then take this access_token to access the resources:

http://localhost:8080/AOuth/admin?access_token=4219a91f-45d5-4a07-9e8e-3acbadd0c23e

Refresh Access_token:

Http://localhost:8080/AOuth/oauth/token?client_id=mobile_1&client_secret=secret_1&grant_type=refresh_ Token&refresh_token=ad18fc89e1424278b675ca05bf8afbb3

   Thanks: Thank you for reading!

Original: http://www.cnblogs.com/0201zcr/p/5328847.html

Spring Security oauth2.0 Implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.