Spring Boot combat filter realizes interface authentication using JWT

Source: Internet
Author: User

Spring Boot combat filter realizes interface authentication using JWT


JWT (JSON Web token)

The user sends the Header, Payload, and Signature to the server, and contains the authentication information (password), after the authentication is returned by the server to a token, after which the user uses the token as the login credential, which is suitable for mobile and API


JWT usage Process



This example is written in the code in the previous articles, please read this article and refer to the previous articles


1, add dependent library JJWT, this article constructs the JWT and the analytic JWT all uses the JJWT library

<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId>< Version>0.6.0</version></dependency>



2, add login to get token, the required authentication information class Loginpara.java

Package Com.xiaofangtech.sunt.jwt;public class Loginpara {private string Clientid;private string username;private String Password;private string Captchacode;private string Captchavalue;public string Getclientid () {return clientId;} public void Setclientid (String clientId) {this.clientid = clientId;} Public String GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public String Getcaptchacode () {return captchacode;} public void Setcaptchacode (String captchacode) {this.captchacode = Captchacode;} Public String Getcaptchavalue () {return captchavalue;} public void Setcaptchavalue (String captchavalue) {this.captchavalue = Captchavalue;}}


3, add to construct JWT and resolve JWT Help class Jwthelper.java

Package Com.xiaofangtech.sunt.jwt;import Java.security.key;import Java.util.date;import Javax.crypto.spec.secretkeyspec;import Javax.xml.bind.datatypeconverter;import Io.jsonwebtoken.Claims;import Io.jsonwebtoken.jwtbuilder;import Io.jsonwebtoken.jwts;import Io.jsonwebtoken.signaturealgorithm;public Class Jwthelper {public static Claims PARSEJWT (String jsonwebtoken, String base64security) {Try{claims Claims = Jwts.parser (). Setsigningkey (Datatypeconverter.parsebase64binary (base64security)). Parseclaimsjws (JsonWebToken). GetBody (); return claims;} catch (Exception ex) {return null;}} public static string CREATEJWT (string name, String userId, String role, string audience, string issuer, long Ttlmillis, St Ring base64security) {Signaturealgorithm signaturealgorithm = signaturealgorithm.hs256; Long Nowmillis = System.currenttimemillis ();D ate now = new Date (nowmillis); Generate signature key byte[] apikeysecretbytes = datatypeconverter.parsebase64binary (base64security); Key Signingkey = new Secretkeyspec (apikeYsecretbytes, Signaturealgorithm.getjcaname ()); Add the parameters that make up the JWT jwtbuilder builder = Jwts.builder (). Setheaderparam ("Typ", "JWT"). Claim ("role", role). C                        Laim ("Unique_name", name). Claim ("userid", UserID). Setissuer (Issuer) . Setaudience (audience). Signwith (Signaturealgorithm, Signingkey);    Add token Expiration Time if (ttlmillis >= 0) {Long Expmillis = Nowmillis + ttlmillis;    Date exp = new Date (expmillis);  Builder.setexpiration (exp). Setnotbefore (now);} Generate Jwtreturn Builder.compact ();} }


4. Add token return result class Accesstoken.java

Package Com.xiaofangtech.sunt.jwt;public class Accesstoken {private string access_token;private string Token_type; Private Long Expires_in;public String Getaccess_token () {return access_token;} public void Setaccess_token (String access_token) {this.access_token = Access_token;} Public String Gettoken_type () {return token_type;} public void Settoken_type (String token_type) {this.token_type = Token_type;} Public long getexpires_in () {return expires_in;} public void setexpires_in (long expires_in) {this.expires_in = expires_in;}}


5, add the interface to get tokens, through the incoming user authentication information (user name, password) for authentication access

Package Com.xiaofangtech.sunt.jwt;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.web.bind.annotation.requestbody;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import Com.xiaofangtech.sunt.bean.userinfo;import Com.xiaofangtech.sunt.repository.userinforepository;import Com.xiaofangtech.sunt.utils.myutils;import Com.xiaofangtech.sunt.utils.resultmsg;import Com.xiaofangtech.sunt.utils.ResultStatusCode; @RestControllerpublic Class Jsonwebtoken {@Autowiredprivate userinforepository userrepositoy; @Autowiredprivate audience audienceentity;@ Requestmapping ("Oauth/token") public Object Getaccesstoken (@RequestBody Loginpara Loginpara) {resultmsg resultmsg;try {if (Loginpara.getclientid () = = NULL | | (Loginpara.getclientid (). CompareTo (Audienceentity.getclientid ()) = 0)) {resultmsg = new resultmsg (ResultStatusCode.INVALID_CLIENTID.getErrcode (), resultstatuscode.invalid_ Clientid.geterrmsg(), null); return resultmsg;} Verification code Check Add//Verify username password userinfo user = Userrepositoy.finduserinfobyname (loginpara.getusername ()) in later chapters, if (user = = null) { resultmsg = new Resultmsg (ResultStatusCode.INVALID_PASSWORD.getErrcode (), resultstatuscode.invalid_ Password.geterrmsg (), null); return resultmsg;} Else{string Md5password = Myutils.getmd5 (Loginpara.getpassword () +user.getsalt ()); if (Md5password.compareto ( User.getpassword ())! = 0) {resultmsg = new resultmsg (ResultStatusCode.INVALID_PASSWORD.getErrcode (), ResultStatusCode.INVALID_PASSWORD.getErrmsg (), null); return resultmsg;}} Assembled accesstokenstring Accesstoken = JWTHELPER.CREATEJWT (Loginpara.getusername (), String.valueof (User.getName ()), User.getrole (), Audienceentity.getclientid (), Audienceentity.getname (), Audienceentity.getexpiressecond () * 1000, Audienceentity.getbase64secret ());//return Accesstokenaccesstoken accesstokenentity = new Accesstoken (); Accesstokenentity.setaccess_token (Accesstoken); Accesstokenentity.setexpires_in (AudienceEntity.getExpiresSecond (); Accesstokenentity.settoken_type ("bearer"); resultmsg = new Resultmsg (ResultStatusCode.OK.getErrcode (), ResultStatusCode.OK.getErrmsg (), accesstokenentity); return resultmsg;} catch (Exception ex) {resultmsg = new resultmsg (ResultStatusCode.SYSTEM_ERR.getErrcode (), resultstatuscode.system_ Err.geterrmsg (), null); return resultmsg;}}}


6. Add Filter with JWT authentication

Package Com.xiaofangtech.sunt.filter;import Java.io.ioexception;import Javax.servlet.filter;import Javax.servlet.filterchain;import Javax.servlet.filterconfig;import Javax.servlet.servletexception;import Javax.servlet.servletrequest;import Javax.servlet.servletresponse;import javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.httpservletresponse;import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.web.context.support.springbeanautowiringsupport;import Com.fasterxml.jackson.databind.objectmapper;import Com.xiaofangtech.sunt.jwt.audience;import Com.xiaofangtech.sunt.jwt.jwthelper;import Com.xiaofangtech.sunt.utils.resultmsg;import Com.xiaofangtech.sunt.utils.resultstatuscode;public class Httpbearerauthorizeattribute implements Filter{@ Autowiredprivate audience audienceentity; @Overridepublic void init (Filterconfig filterconfig) throws Servletexception {//TODO auto-generated method Stubspringbeanautowiringsupport.processinjectionbasedonservLetcontext (this, Filterconfig.getservletcontext ());} @Overridepublic void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {//TODO auto-generated method stubresultmsg resultmsg; HttpServletRequest HttpRequest = (httpservletrequest) request;  String auth = Httprequest.getheader ("Authorization"), if (auth! = null) && (Auth.length () > 7)) {String headstr             = auth.substring (0, 6). toLowerCase (); if (Headstr.compareto ("bearer") = = 0) {auth = auth.substring (7, Auth.length ()); if (JWTHELPER.PARSEJWT (auth, audienceentity.getbase64secret ()) = null) {Chain.dofilter (req            Uest, response);            Return  }}}httpservletresponse HttpResponse = (httpservletresponse) response;httpresponse.setcharacterencoding ("UTF-8"); Httpresponse.setcontenttype ("Application/json; Charset=utf-8 "); Httpresponse.setstatus (httpservletresponse.sc_unauthorized); Objectmapper mapper = new ObjectmappeR (); resultmsg = new Resultmsg (ResultStatusCode.INVALID_TOKEN.getErrcode (), resultstatuscode.invalid_ Token.geterrmsg (), null), Httpresponse.getwriter (). Write (Mapper.writevalueasstring (resultmsg)); return;} @Overridepublic void Destroy () {//TODO auto-generated method stub}}


7. Register the filter at the entrance

Package Com.xiaofangtech.sunt;import Java.util.arraylist;import Java.util.list;import Org.springframework.boot.springapplication;import org.springframework.boot.autoconfigure.SpringBootApplication; Import Org.springframework.boot.context.embedded.filterregistrationbean;import Org.springframework.boot.context.properties.enableconfigurationproperties;import Org.springframework.context.annotation.bean;import Com.xiaofangtech.sunt.filter.HTTPBasicAuthorizeAttribute; Import Com.xiaofangtech.sunt.filter.httpbearerauthorizeattribute;import com.xiaofangtech.sunt.jwt.audience;@ Springbootapplication@enableconfigurationproperties (audience.class) public class Springrestapplication {public static void Main (string[] args) {Springapplication.run (springrestapplication.class, args);} @Bean public Filterregistrationbean Basicfilterregistrationbean () {Filterregistrationbean Registrationbean = new Filte Rregistrationbean (); Httpbasicauthorizeattribute httpbasicfilter = new Httpbasicauthorizeattribute (); RegiStrationbean.setfilter (Httpbasicfilter);    list<string> urlpatterns = new arraylist<string> ();    Urlpatterns.add ("/user/getuser");    Registrationbean.seturlpatterns (Urlpatterns);    return Registrationbean; } @Beanpublic Filterregistrationbean Jwtfilterregistrationbean () {Filterregistrationbean Registrationbean = new Filterregistrationbean (); Httpbearerauthorizeattribute httpbearerfilter = new Httpbearerauthorizeattribute (); Registrationbean.setfilter ( Httpbearerfilter);    list<string> urlpatterns = new arraylist<string> ();    Urlpatterns.add ("/user/getusers");    Registrationbean.seturlpatterns (Urlpatterns); return Registrationbean;}}

8. Add method class to get MD5 myutils
Package Com.xiaofangtech.sunt.utils;import Java.security.messagedigest;public class Myutils {public static String GetMD5 (String inStr) {        messagedigest MD5 = NULL;        try {            MD5 = messagedigest.getinstance ("MD5");        } catch (Exception e) {                        e.printstacktrace ();            Return "";        }        char[] Chararray = Instr.tochararray ();        byte[] ByteArray = new Byte[chararray.length];         for (int i = 0; i < chararray.length; i++)            bytearray[i] = (byte) chararray[i];         byte[] md5bytes = Md5.digest (ByteArray);         StringBuffer hexvalue = new StringBuffer ();         for (int i = 0; i < md5bytes.length; i++) {            int val = ((int) md5bytes[i]) & 0xFF;            if (Val < hexvalue.append)                ("0");            Hexvalue.append (Integer.tohexstring (Val));        }         return hexvalue.tostring ();    }}

9. Add the error code in the return information class

        Invalid_clientid (30003, "INVALID CLIENTID"), Invalid_password (30004, "User name or PASSWORD is incorrect"), invalid_ CAPTCHA (30005, "Invalid CAPTCHA or CAPTCHA overdue"), Invalid_token (30006, "Invalid TOKEN");



10, the code involved in the audience class, defined in the previous article, this article no longer repeat the description


11, the overall structure of the Code



12. Testing

1) Get token, incoming user authentication information



Authentication by returning token information




2) Use the token obtained above for the interface call

Do not use token, get token error, or token expires



When using the correct token



Spring Boot combat filter realizes interface authentication using JWT

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.