Nineth Chapter Springcloud OAUTH2 Certification Center-zuul Network close to add certification

Source: Internet
Author: User
Tags oauth
This chapter complete source address: Https://github.com/kwang2003/springcloud-study-ch09.git 1. Project Summary The content of this chapter is based on the seventh chapter of the code as a https://github.com/ Kwang2003/springcloud-study-ch08.git. Through the eighth chapter of the study, we have already based on JWT upgraded OAuth2 authentication server, in this chapter, we will give the previous Zuul gateway plus OAuth2 authentication function, so that all access after a security certification to continue. The system architecture is the same as the previous chapter and remains unchanged
2.oauth2 Project Change a) to add/UAA access context for OAUTH2 project after configuration, the Oauth2 project's access address will be added/UAA this context, plus this context is mainly for the latter step forwarding rules to use server.context-path= /uaa
b get public key by looking at the Jwtaccesstokenconverter source to see that the Vertify key is a string of BASE64 encoded PublicKey:
Add a test class publickeytest, and follow the rules to generate this string, the code is as follows:
The key result of the output is the-----BEGIN public Key-----miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeaozqfhahqezguwbeslrcom9dmivm/ fhejlg7vk3coz1xum49p4pc+pny3nm+wl/wm8qqdynjpetzciltldw60rqa/+osw599skmusgf7ryxi9y4n1n4h0k9jlbdz9n2/ 5miwwpdwrbsigglxp/nish4t2gj6luzumj4cskiju8p12s5tjeq3n+pgyby+g8zwzyb1dr3lssqatoqv1/xh+kpeesataaxjsfa/ swpaxdznm5jgsjq1/fejyf2e0yakbv/nqhniqqnucr/stfbn/ Sgloes1daj8nimtoiklqejqjvjcsdoc75f2n3ik72dgavzksntfedsvyghiootbtwqidaqab-----End Public KEY-----3. Gateway Project Retrofit Springcloud-zuul a) Add spring-cloud-starter-oauth2 and JWT <dependency> <groupId> Org.springframework.cloud</groupid> <artifactId>spring-cloud-starter-oauth2</artifactId> </ dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId> spring-security-jwt</artifactid> </dependency> B) Modify the system configuration entry to add JWT and OAUTH2 Security certification related configuration, as follows Security.basic.enabled=false Security.oauth2.sso.loginpath=/login security.oauth2.client.accesstokenuri=http:// oauth2/uaa/oauth/tOken security.oauth2.client.userauthorizationuri=/uaa/oauth/authorize security.oauth2.client.clientid=client Security.oauth2.client.clientsecret=secret security.oauth2.resource.jwt.keyvalue=\-----BEGIN public KEY-----\ miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeaozqfhahqezguwbeslrcom9dmivm/fhejlg7vk3coz1xum49p4pc+pny3nm+wl/ wm8qqdynjpetzciltldw60rqa/+osw599skmusgf7ryxi9y4n1n4h0k9jlbdz9n2/5miwwpdwrbsigglxp/ nish4t2gj6luzumj4cskiju8p12s5tjeq3n+pgyby+g8zwzyb1dr3lssqatoqv1/xh+kpeesataaxjsfa/swpaxdznm5jgsjq1/ Fejyf2e0yakbv/nqhniqqnucr/stfbn/sgloes1daj8nimtoiklqejqjvjcsdoc75f2n3ik72dgavzksntfedsvyghiootbtwqidaqab\----- End public KEY-----Security.oauth2.resource.id=zuul Security.oauth2.resource.serviceid=${prefix:}zuul Where the red highlight is set for the previous step through the Publickeytest output C) zuulapplication Resourceserver Oauth2 contains four core roles Resource Owner----is usually a user, such as John Resource Server----resource server, storage of specific data, in this project is Zuul (in fact, the various micro-services, but we use Zuul Unified agent, so the Resource Server set up in the Zuul, This is also the point of increasing the Zuul-we don't need to add these configurations to each of the micro services repeatedly, but to add one at the Zuul Unified exit.Authorization Server----Authentication servers, this project is SPRINGCLOUD-OAUTH2 service Client---Need to use the OAUTH2 server for integrated Third-party applications, If our website rrs.com to use QQ joint login, then rrs.com is a client, in the project, the client's information is defined in the memory to make zuulapplication become resourceserver very simple, Add @enableresourceserver annotation on class: Package Com.pachiraframework.springcloud.zuul;
Import org.springframework.boot.SpringApplication; Import org.springframework.boot.autoconfigure.SpringBootApplication; Import org.springframework.cloud.client.discovery.EnableDiscoveryClient; Import Org.springframework.cloud.netflix.zuul.EnableZuulProxy; Import Org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
@EnableZuulProxy @EnableResourceServer @EnableDiscoveryClient @SpringBootApplication public class Zuulapplication { public static void Main (string[] args) {Springapplication.run (zuulapplication.class, args);} And to add a userinforesttemplate Bean @Bean userinforesttemplatecustomizer Userinforesttemplatecustomizer ( Loadbalancerinterceptor loadbalancerinterceptor) {return template-> {list<clienthttprequestinterceptor> Interceptors = new arraylist<> (); Interceptors.add (Loadbalancerinterceptor); Accesstokenproviderchain Accesstokenproviderchain = Stream. of (New Authorizationcodeaccesstokenprovider (), New Implicitaccesstokenprovider (), New Resourceownerpasswordaccesstokenprovider (), New Clientcredentialsaccesstokenprovider ()). PEEK (TP-> tp.setinterceptors (interceptors)). Collect ( Collectors.collectingandthen (Collectors.tolist (), accesstokenproviderchain::new)); Template.setaccesstokenprovider (Accesstokenproviderchain); }; }
d) Add a Dynamicoauth2clientcontextfilter
(f) Increased security configuration securityconfiguration package com.pachiraframework.springcloud.zuul.config;
Import java.io.IOException; Import Java.util.regex.Pattern;
Import Javax.servlet.Filter; Import Javax.servlet.FilterChain; Import javax.servlet.ServletException; Import Javax.servlet.http.Cookie; Import Javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.HttpServletResponse;
Import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; Import Org.springframework.context.annotation.Bean; Import org.springframework.context.annotation.Configuration; Import Org.springframework.context.annotation.Primary; Import Org.springframework.core.annotation.Order; Import Org.springframework.security.authentication.AuthenticationManager; Import org.springframework.security.config.annotation.web.builders.HttpSecurity; Import Org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; Import Org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; Import Org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager; Import Org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter; Import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; ImpORT Org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; Import Org.springframework.security.web.csrf.CsrfFilter; Import Org.springframework.security.web.csrf.CsrfToken; Import Org.springframework.security.web.csrf.CsrfTokenRepository; Import Org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; Import Org.springframework.security.web.util.matcher.AntPathRequestMatcher; Import Org.springframework.security.web.util.matcher.RequestMatcher; Import Org.springframework.web.filter.OncePerRequestFilter;
@Configuration @EnableOAuth2Sso @Order (value = 0) public class Securityconfiguration extends Websecurityconfigureradapter {private static final string csrf_cookie_name = "Xsrf-token"; private static final string CS Rf_header_name = "X-xsrf-token";
@Autowired private resourceservertokenservices resourceservertokenservices;
@Bean @Primary public Oauth2clientcontextfilter dynamicoauth2clientcontextfilter () {return new Dynamicoauth2clientcontextfilter (); }
@Override public void Configure (Httpsecurity http) throws Exception {http.authorizerequests (). Antmatchers ("/uaa/**", " /login "). Permitall (). Anyrequest (). authenticated () and (). CSRF (). Requirecsrfprotectionmatcher (Csrfrequestmatcher ()). Csrftokenrepository (Csrftokenrepository ()). and (). Addfilterafter (Csrfheaderfilter (), Csrffilter.class). Addfilterafter (Oauth2authenticationprocessingfilter (), Abstractpreauthenticatedprocessingfilter.class). Logout () . Permitall (). Logoutsuccessurl ("/"); }
Private Oauth2authenticationprocessingfilter Oauth2authenticationprocessingfilter () { Oauth2authenticationprocessingfilter Oauth2authenticationprocessingfilter = new Oauth2authenticationprocessingfilter (); Oauth2authenticationprocessingfilter.setauthenticationmanager (Oauthauthenticationmanager ()); Oauth2authenticationprocessingfilter.setstateless (FALSE);
return oauth2authenticationprocessingfilter; }

Private AuthenticationManager Oauthauthenticationmanager () {Oauth2authenticationmanager Oauth2authenticationmanager = new Oauth2authenticationmanager (); Oauth2authenticationmanager.setresourceid ("Zuul"); Oauth2authenticationmanager.settokenservices (resourceservertokenservices); Oauth2authenticationmanager.setclientdetailsservice (NULL);
return oauth2authenticationmanager; }
Private Requestmatcher Csrfrequestmatcher () {Return to New Requestmatcher () {//Always allow the HTTP get method private fi NAL Pattern allowedmethods = pattern.compile ("^" (get| head| options| TRACE) $ ");
Disable CSFR Protection on the following urls:private final antpathrequestmatcher[] requestmatchers = {new Antpathreq Uestmatcher ("/uaa/**")};
@Override public boolean matches (HttpServletRequest request) {if Allowedmethods.matcher (Request.getmethod ()). Matches ()) {return false;}
for (Antpathrequestmatcher matcher:requestmatchers) {if (matcher.matches. Request) {return false;}} return true; } }; }
private static Filter Csrfheaderfilter () {return new Onceperrequestfilter () {@Override protected void dofilterinternal (H Ttpservletrequest request, HttpServletResponse response, Filterchain Filterchain) throws Servletexception, IOException {

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.