Golang中使用 JWT认证来 保障Restful JSON API的安全(英文) - 推酷

所需积分/C币:20 2017-11-22 17:30:27 494KB PDF
92
收藏 收藏
举报

Golang中使用 JWT认证来 保障Restful JSON API的安全(英文) - 推酷
2017/517 Galang屮使用JWT认证来保障 Restful jsON AP的安仝(英文)-推酷 2. You can see how the parts work together since modules have to be injected before use 3. Code is reusable since all of the necessary functionality is contained inside the module 4. Testing your code is much easier Here is how we want our file structure to look like OPEN FILES s P server.go c SEti 9U Fnl ERS package main 7 api. jt. auth □ api jwt. auth/routers" p□api PB controllers CoEV auth controller. go 45678g api. Jwt. authy'sett1ngs github. com/ codegangsta/negroni" net/http L hello_controller.gD 18 func main()t b D cere Cn settings, Init() p口 provIson router vE reuters nV m免 routers. InitRoutes(I grond Classic( 14 n. UseHandLer( router) 5 authentication.go httpListenandserve(":500g",n) 5 router.go vB models 5 users go p□ settngs 口tes L gitignore v Creating Routers The code shown below creates a/ route assigning each Foute with his controller who runs when that endpoint is called routers/router. go package routers import github. com/gorilla/mux func InitRoutes()*mux Router i router :=mux. NewRouter() router= SetHelloRoutes (router) router SetAuthenticationRoutes(router) return router routers/authentication. go package routers import api jwt. auth/controllers api. jwt. auth/core/authentication github. com/codegangsta/negroni github. com/gorilla/mux 2017/517 Galang屮使用JWT认证来保障 Restful jsON AP的安仝(英文)-推酷 func SetAuthenticationRoutes(router *mux Router )*mux, Router router. HandleFunc("/token-auth", controllers. LoginMethods("POST router Handle(/refresh-token-auth", negroni. New( negroni. Handler Func(authentication. RequireTokenAuthentication) negroni. Handler Func(controllers. RefreshToken )).Methods("GET") router Handle("/logout", negroni. New( negroni, Handler Func(authentication, RequireTokenAuthentication) negroni. Handler Func(controllers. Logout) )).Methods("GET") return router routers/hello. go package routers import api jwt. auth/controllers github. com/codegangsta/negroni github. com/gorilla/mux func SetHelloRoutes(router *mux Router)*mux Router i router Handle( /test/hello", negroni. New( negroni. Handler Func(controllers. HelloController), )) Methods( " GET") return router Now, you will also notice now that the endpoint "/test/hello" has no"Require Token Authentication"mid dleware(at least for now) Creating Controllers Let's create our controller's package to manage requests and responses. Controllers will interact with ur services controllers/auth controller. go package controllers import api. jwt. auth/services api jwt. auth/services/models encoding/ison net/http 2017/517 Galang屮使用JWT认证来保障 Restful jsON AP的安仝(英文)-推酷 funcLogin(whttpResponsewriter,r*http.Request requestUser new(models User) decoder json New Decoder (r Body decoder Decode(&requestUser) responseStatus, token : services Login (requestUser) W Header(). Set("Content-Type","application/ison") W.WriteHeader(responsestatus) W, Write(token) funcRefreshtoken(whttpResponsewriter,r*http.RequestnexthttpHandlerfunc)i requestUser new(models User) decoder json New Decoder(r Body) decoder Decode(&requestUser) W, Header () Set(" Content-Type",application/ison WWrite(services. RefreshToken(requestUser)) funcloGout(whttprEsponsewriter,r*http.RequestnexthttpHandlerfunc)i err services Logout(r) W Header(). Set(" Content-Type","application/json") if err ! nil t W.writehEader(http.StatusinternalservererrOr) y else t W.writeHeader(http.Statusok) controllers/hello controller. go package controllers mport net/http funcHellocontroller(whttpResponsewriter,rsh ttpRequestnexthttpHandlerfunc W,write([]byte( Hello, world! ") Creating models Now that we have routes and controllers in place, it's time to create a basic user model that we can u se to authenticate requests services/models/users. go package models type User struct t UUID string json: uuid form: Username string json: username" form:"username 2017/517 Galang屮使用JWT认证来保障 Restful jsON AP的安仝(英文)-推酷 Password string json:"password" form:" password Creating Services services/auth service. go package services import pijwt. auth/api/parameters api jwt. auth/core/authentication api. jwt. auth/services/models encoding/ison jwtgithub. com/grijalva/jwt-go net/http func Login(requestUser *models, User) (int, [byte)t authBackend authentication InitJWTAuthentication Backend() if authBackend Authenticate (requestuser)i token, err : =authBackend Generate Token (requestUser, UUID) if err ! nil i returnhttpStatusinternalservererrOr,[lbyte(") j else i response, := json. Marshal(parameters. TokenAuthentication token)) returnhttpstatusok,response returnhttpStatusunauthorized,[lbyte(") func RefreshToken (requestUser *models User)[byte i authBackend authentication Init]WTAuthenticationBackend() token, err authBackend GenerateToken(requestUser. UUID) if err ! nil t panic(err) response, err json Marshal(parameters. TokenAuthenticationftoken) if err ! nil t panic(err) return response funcLogout(req*http.Request)errori authBackend : authentication InitJWTAuthenticationBackend() tokenRequest, err : jwt ParseFromRequest(req, func(token *jwt. Token) (interfacet] rror) return authBackend. PublicKey, nil if err ! nil i return err tokenString req Header. Get("Authorization") 2017/517 Galang屮使用JWT认证来保障 Restful jsON AP的安仝(英文)-推酷 return authBackend Logout(tokenString, tokenRequest) Web server server. go package main import api. jwt. auth/routers api jwt. auth/settings github. com/codegangsta/negroni net/http func main( i settings.Itito) router: =routers. InitRquyes() ne dopi classic() n. UseHanpler(router httpListenandserve(":5000",n) Let's try our luck! If we try to test it, we will obtain a valid response from server Haccsat:applicationDjson-hcEntont-type:acplicataon/jsen"-kGethttp://122..68.14218:saea/teat/hello ●。● 12161410 Hello, world At this moment we have not needed to send a valid token to the server to obtain a valid response Applying authentication with JWT As we can see right now, our API endpoint "/test/hello"is insecure. Let's add our " Require Token Auth entication"middleware to protect it. core/authentication/middlewares. go package authentication import jwt github. com/grijalva/jwt-go net/http funcRequiretokenauthentication(rwhttpResponsewriter,req*http.RequestnexthttpHandler unc authBackend : InitJWTAuthenticationBackend() 2017/517 Galang屮使用JWT认证来保障 Restful jsON AP的安仝(英文)-推酷 regj func(token *jwt. Token) (interface, error)t return authBackend. PublicKey, nil if err = nil & token valid & I authBackend, IsInBlacklist(req. Header. Get("Authorization ))i next(rw, req) y else i rw.Writeheader(http.Statusunauthorized) routers/nello. go package routers import api, jwt. auth/controllers api jwt. auth/core/authentication github. com/codegangsta/negroni github. com/gorilla/mux func SetHelloRoutes(router *mux Router)*mux Router i router Handle("/test/hello", negroni. New( negroni. HandlerFunc(authentication, Require TokenAuthen tication) negroni, Handler Func(controllers. HelloController )) Methods( GET") return router Now, our APi test endpoint is secured and it's necessary a valid token to obtain a valid response Let's try our luck again! If we can try again without a valid token we'll receive a unauthorized error response sh-3。2 h-3a2dcurl-i-hacccotiapplication/iaon-h"cantent-trpclapelicatiOn/json-kGefhttprisla168.1.21e15880/icat/hello Http/1.1 4a: Wnoutherted or the last time! if we add an authorization header to our request we'll obtain a valid response from the server: 1. Firstly we need to obtain a valid token A 2. Finally, we can do the request with our valid token 2017/517 Galang屮使用JWT认证来保障 Restful jsON AP的安仝(英文)-推酷 Session control Token Logout The last step, or bonus step, is how we can manage user logout and invalidate his token Imagine that an user token has been captured from third party or simply an user wants to logout from a client and we don ' t want his token to be valid again. In this way, we force he to do login again for sec urity reasons To solve this problems, we'l use Redis to store all invalid tokens until their expiration For that, we need the methods: Logout and lsInblacklist. The first method sets token 's value in Redis with his expiration and the second method checks if a token is stored in redis core/authentication/jwt backend. go func(backend *]WTAuthenticationBackend) Logout(tokenString string, token *jwt. Token) error i redisConn redis Connect() expiration backend getTakenRemainingValidity(taken Claims[" exp]) return redisConn SetValue(tokenString, tokenstring, expiration) func(backend *JWTAuthenticationBackend) IsInBlacklist(token string) bool t redisConn redis Connect() redisToken,:=redis Conn GetValue(token) if redisToken = nil i return false return true Can I get all the code? Yes! of course. Here is a repo with all of the code and tests https:/github.com/brainattica/golang-jwt-authentication-api-sample Summary That's all you have to do. JWT is a fantastic and simple way to communicate trusted information acro sS untrusted channels. Hope you find a good use for it soon! As well as I hope you found this post useful and helped you Code less, compile quicker execute faster = have more fun! 2017/517 Galang屮使用JWT认证来保障 Restful jsON AP的安仝(英文)-推酷 http://www.tuicool.com/articles/znmzf3 10/10

...展开详情
试读 10P Golang中使用 JWT认证来 保障Restful JSON API的安全(英文) - 推酷
立即下载 低至0.43元/次 身份认证VIP会员低至7折
一个资源只可评论一次,评论内容不能少于5个字
您会向同学/朋友/同事推荐我们的CSDN下载吗?
谢谢参与!您的真实评价是我们改进的动力~
关注 私信
上传资源赚钱or赚积分
最新推荐
Golang中使用 JWT认证来 保障Restful JSON API的安全(英文) - 推酷 20积分/C币 立即下载
1/10
Golang中使用 JWT认证来 保障Restful JSON API的安全(英文) - 推酷第1页
Golang中使用 JWT认证来 保障Restful JSON API的安全(英文) - 推酷第2页

试读结束, 可继续读1页

20积分/C币 立即下载