Springboot's JWT verification

Source: Internet
Author: User
Tags compact

about what is JWT (Json Web Token)

JWT is a JSON-based open standard that executes in order to pass claims across a network application environment. The token is designed to be compact and secure, especially for SSO scenarios.
A JWT statement is typically used to pass authenticated user identity information between the identity provider and the service provider.

What does a JWT look like

Eyjhbgcioijiuzuxmij9.eyjzdwiioij0zxn0mdayiiwizxhwijoxntewotcwmju4fq._ foqy5l44hodu3djxh762lnutlnqh15fdcuerdsedpmskgkvscjoyxqntbkdsh3n-c83_pdew5t6bdorgru_kw

The composition of the JWT

JWT usually consists of three parts, header information (header), message body (body), signature (signature)
Header information Specifies the signature algorithm used by JWT

HEADER={ALG=HS512}

The message body contains the intent of the JWT, exp is the token expiration time

Body={sub=testusername, exp=1510886546}

The signature is generated by the private key

Signature=kwq8a_b6wmqhorei-gfr5rrpmpl7qoshzjn0vffxpxc1yfw6bfvrliap9c4unxlqd3wrxo3mw_ddidgln5lh9q

Integrating JWT with Springboot

JWT official website

Springboot official website

Reference dependency
  <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-web</artifactId>  </dependency>  <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-security</artifactId>  </dependency>  <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-actuator</artifactId>  </dependency>  <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-devtools</artifactId>  </dependency>  <dependency>      <groupId>io.jsonwebtoken</groupId>      <artifactId>jjwt</artifactId>      <version>0.7.0</version>  </dependency>
Building a common Rest interface
  @RestController  @RequestMapping("/employee")  public class EmployeeController {      @GetMapping("/greeting")       public String greeting() {           return "Hello,World!";       }   }
Jwtloginfilter
public class Jwtloginfilter extends Usernamepasswordauthenticationfilter {private AuthenticationManager   AuthenticationManager; Public Jwtloginfilter (AuthenticationManager authenticationmanager) {This.authenticationmanager = AuthenticationMana   Ger        } @Override Public authentication attemptauthentication (httpservletrequest request, httpservletresponse response)       Throws Authenticationexception {Employee employee = new Employee (); Return Authenticationmanager.authenticate (new Usernamepasswordauthenticationtoken (employ       Ee.getusername (), Employee.getpassword (), New arraylist<> ())   ); } @Override protected void successfulauthentication (HttpServletRequest request, httpservletresponse response, Filterc           Hain chain, authentication authresult) throws IOException, servletexception {String token = Jwts.builder () . Setsubject ((User) Authresult.getprincipAl ()). GetUserName ()). SetExpiration (New Date (System.currenttimemillis () + * ()). Signwith (S       ignaturealgorithm.hs512, "Jwtsecret"). Compact ();  Response.AddHeader ("Authorization", Jwtutils.gettokenheader (token)); }

}

Jwtauthenticationfilter
  public class Jwtauthenticationfilter extends Basicauthenticationfilter {public Jwtauthenticationfilter (  AuthenticationManager AuthenticationManager) {super (AuthenticationManager); } @Override protected void dofilterinternal (HttpServletRequest request, httpservletresponse response, Filterchain chain      ) throws IOException, servletexception {String header = Request.getheader ("Authorization"); if (header = = NULL | |!header.startswith (JWTUTILS.GETAUTHORIZATIONHEADERPREFIX ())) {Chain.dofilter (Request, RESP         Onse);      Return      } Usernamepasswordauthenticationtoken Authenticationtoken = Getusernamepasswordauthenticationtoken (header);      Securitycontextholder.getcontext (). Setauthentication (Authenticationtoken);  Chain.dofilter (request, response); } Private Usernamepasswordauthenticationtoken Getusernamepasswordauthenticationtoken (String token) {String user = J Wts.parser (). Setsigningkey ("Privatesecret"). ParseclaImsjws (Token.replace (Jwtutils.getauthorizationheaderprefix (), "")). GetBody (). Getsubject ();      if (null! = user) {return new Usernamepasswordauthenticationtoken (user, NULL, new arraylist<> ());  } return null; }  }
Securityconfiguration
  @Configuration  @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {    @Override    public void configure(WebSecurity web) throws Exception {          super.configure(web);    }    @Override    protected void configure(HttpSecurity http) throws Exception {      http.cors().and().csrf().disable().authorizeRequests()              .anyRequest().authenticated()              .and()              .addFilter(new JwtLoginFilter(authenticationManager()))              .addFilter(new JwtAuthenticationFilter(authenticationManager()));    }  }
Using the Postman test

First we test the/employee/greeting response as follows:

{
"Timestamp": 1510887634904,
"Status": 403,
"Error": "Forbidden",
"Message": "Access Denied",
"Path": "/employee/greeting"
}

Obviously, the status code is 403, now if we log in to get token before testing it, the test is as follows

Once the login is successful, we can see that the headers has a JWT

Authorization→bearer EyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0VXNlcm5hbWUiLCJleHAiOjE1MTA4ODkxMDd9.FtdEM0p84ff5CzDcoiQhtm1MF_ Nfdh2ij1jspxltqhucisizydou40osfoxam9f1exevw2gzdqmarvwmk6ho1a

Since postman does not support custom headers in general this time we need to download a plugin to open interceptor and put authorization into the header to continue testing:

Then we find that we have successfully returned to hello,world!

Last attached code github address: Source download

Springboot's JWT verification

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.