Use spring security and OAuth2 for RESTful service safety certification

Source: Internet
Author: User
Tags couchbase oauth git clone

This tutorial shows how to set up a OAuth2 service to protect rest resources. Source code download GitHub. (https://github.com/iainporter/oauth2-provider) You can download the source code and start writing a service that is protected by the OAuth method. This source contains features:

* User Registration and Login
* Email Verification
* Password lost

The following techniques have been adopted:

* OAuth2 Protocol
* Spring Security
* Spring Integration
* Spring Data
* Jersey/jax-rs
* Gradle/groovy
* MongoDB

Build your project in the following ways:

> Git clone [email protected]:iainporter/oauth2-provider.git
> CD Oauth2-provider
>./gradlew Clean Build Integrationtest

To run the Web project:

This application is based on MongoDB as the persistence layer, before running the application to confirm that Mongod is running on port 27017.

To run the command:

>./gradlew tomcatrun

Open http://localhost:8080/oauth2-provider/index.html in Browser

1. Create a User:

Curl-v-X POST \
-h "Content-type:application/json" \
-H "Authorization:basic mzuzyjmwmmm0ndu3ngy1njuwndu2oddlntm0ztdknme6mjg2oti0njk3ztyxnwe2nzjhnjq2ytq5mzu0nty0nmm= " \
-d ' {"user": {"EmailAddress": "[email protected]"}, "password": "Password"} ' \
' Http://localhost:8080/oauth2-provider/v1.0/users '

The result should be:

{"Apiuser":
{"EmailAddress": "[email protected]",
"FirstName": null,
"LastName": null,
"Age": null,
"id": "8a34d009-3558-4c8c-a8da-1ad2b2a393c7",
"Name": "[email protected]"},
"Oauth2accesstoken":
{"Access_token": "7e0e4708-7837-4a7e-9f87-81c6429b02ac",
"Token_type": "Bearer",
"Refresh_token": "D0f248ab-e30f-4a85-860c-bd1e388a39b5",
"Expires_in": 5183999,
"Scope": "Read Write"
}
}

2. Request an Access token:

Curl-v-X POST \
-h "Content-type:application/json" \
-H "Authorization:basic mzuzyjmwmmm0ndu3ngy1njuwndu2oddlntm0ztdknme6mjg2oti0njk3ztyxnwe2nzjhnjq2ytq5mzu0nty0nmm= " \
' Http://localhost:8080/oauth2-provider/oauth/token?grant_type=password&[email protected]&password= Password

The result should be:

{
"Access_token": "a838780e-35ef-4bd5-92c0-07a45aa74948",
"Token_type": "Bearer",
"Refresh_token": "AB06022F-247C-450A-A11E-2FFAB116E3DC",
"Expires_in": 5183999
}

3. Refresh a token:

Curl-v-X POST \
-h "Content-type:application/json" \
-H "Authorization:basic mzuzyjmwmmm0ndu3ngy1njuwndu2oddlntm0ztdknme6mjg2oti0njk3ztyxnwe2nzjhnjq2ytq5mzu0nty0nmm= " \
' Http://localhost:8080/oauth2-provider/oauth/token?grant_type=refresh_token&refresh_token= AB06022F-247C-450A-A11E-2FFAB116E3DC '

The result should be:

{
"Access_token": "4835cd11-8bb7-4b76-b857-55c6e7f36fc4",
"Token_type": "Bearer",
"Refresh_token": "AB06022F-247C-450A-A11E-2FFAB116E3DC",
"Expires_in": 5183999
}

Web Context

A jersey handles all resource calls:

    1. <servlet-mapping>
    2. <servlet-name>jersey-servlet</servlet-name>
    3. <url-pattern>/*</url-pattern>
    4. </servlet-mapping>

The Spring servlet handles all OAuth calls:

    1. <servlet-mapping>
    2. <servlet-name>spring</servlet-name>
    3. <url-pattern>/oauth/*</url-pattern>
    4. </servlet-mapping>

Spring security Mates define a filter:

    1. <filter>
    2. <filter-name>springSecurityFilterChain</filter-name>
    3. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    4. <init-param>
    5. <param-name>contextAttribute</param-name>
    6. <param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.spring</param-value>
    7. </init-param>
    8. </filter>

To filter all URLs in the root directory:

    1. <filter-mapping>
    2. <filter-name>springSecurityFilterChain</filter-name>
    3. <url-pattern>/*</url-pattern>
    4. </filter-mapping>

Configuring the OAuth Process
    1. <oauth:authorization-server client-details-service-ref= "Client-details-service" token-services-ref= " Tokenservices ">
    2. <oauth:refresh-token/>
    3. <oauth:password/>
    4. </oauth:authorization-server>

The default token endpoint is/oauth/token, with only password flow and refresh token support.

Protect token Endpoints

To protect the token endpoint with spring security:

    1. xmlns= "Http://www.springframework.org/schema/security" >
    2. <anonymous enabled= "false"/>
    3. <access-denied-handler ref= "Oauthaccessdeniedhandler"/>

The following configuration authorizes the Authentication manager and Client services:

  1. <bean id= "Clientcredentialstokenendpointfilter"
  2. class= "Org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter" >
  3. <property name= "AuthenticationManager" ref= "Clientauthenticationmanager"/>
  4. </bean>
  5. <authentication-manager id= "Clientauthenticationmanager" xmlns= "http://www.springframework.org/schema/security" >
  6. <authentication-provider user-service-ref= "Client-details-user-service"/>
  7. </authentication-manager>
  8. <bean id= "Client-details-user-service" class= " Org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService ">
  9. <constructor-arg ref= "Client-details-service"/>
  10. </bean>
Configure the User licensing service

Resource Owner Password Flow needs to manage the user's Authorization Manager

    1. <bean id= "Passwordencoder" class= "Org.springframework.security.crypto.password.StandardPasswordEncoder"/>
    2. <sec:authentication-manager alias= "Userauthenticationmanager" >
    3. <sec:authentication-provider user-service-ref= "UserService" >
    4. <sec:password-encoder ref= "Passwordencoder"/>
    5. </sec:authentication-provider>
    6. </sec:authentication-manager>

The password Password encoder is used to encrypt the password. User Services must implement a userdetailsservice that can be returned to users based on their user name.

    1. @Override
    2. Public userdetails Loaduserbyusername (String username) throws Usernamenotfoundexception {
    3. Notnull (username, "Mandatory argument ' username ' missing.");
    4. User user = Userrepository.findbyemailaddress (username.tolowercase ());
    5. if (user = = null) {
    6. throw new Authenticationexception ();
    7. }
    8. return user;
    9. }
Configure token Service
    1. <bean id= "tokenservices" class= "Org.springframework.security.oauth2.provider.token.DefaultTokenServices" >
    2. <property name= "Tokenstore" ref= "Tokenstore"/>
    3. <property name= "Supportrefreshtoken" value= "true"/>
    4. <property name= "Clientdetailsservice" ref= "Client-details-service"/>
    5. </bean>
Securing Resource access
    1. <oauth:resource-server id= "Resourceserverfilter" token-services-ref= "Tokenservices"/>
Core Services

This service provides information based on access tokens for users. URL format:

/v1.0/users/{id}/someresource

  1. @Path ("/v1.0/me")
  2. @Component
  3. @Produces ({Mediatype.application_json})
  4. @Consumes ({Mediatype.application_json})
  5. public class Meresource extends BaseResource {
  6. @RolesAllowed ({"Role_user"})
  7. @GET
  8. Public Apiuser getUser (final @Context securitycontext SecurityContext) {
  9. User Requestinguser = Loaduserfromsecuritycontext (SecurityContext);
  10. if (Requestinguser = = null) {
  11. throw new Usernotfoundexception ();
  12. }
  13. return new Apiuser (Requestinguser);
  14. }
  15. Protected User Loaduserfromsecuritycontext (SecurityContext securitycontext) {
  16. Oauth2authentication Requestinguser = (oauth2authentication) securitycontext.getuserprincipal ();
  17. Object principal = Requestinguser.getuserauthentication (). Getprincipal ();
  18. User user = null;
  19. if (principal instanceof User) {
  20. user = (user) principal;
  21. } else {
  22. user = Userrepository.findbyemailaddress ((String) principal);
  23. }
  24. return user;
  25. }
  26. }

To test this application, start:

>./gradlew tomcatrun

Test:

Curl-v-X GET \
-h "Content-type:application/json" \
-H "Authorization:bearer [your token here]" \
' Http://localhost:8080/oauth2-provider/v1.0/me '

Reference: Https://github.com/tcompiegne/couchbase-token-store-spring-oauth2

Https://github.com/tcompiegne/oauth2-server-spring-couchbase

Transferred from: http://www.jdon.com/dl/best/securing-rest-services-with-spring.html.html

Use spring security and OAuth2 for RESTful service safety certification

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.