The application scenario, at the method level to authenticate the call, such as the API interface has a user uniquely labeled Accesstoken, for each request with Accesstoken can be added to the method of a interceptor, the user to obtain this request, stored in the request or Session field.
In python , the adorner can be used in Python flask to preprocess the method for permission handling
Take a look at an example and use @access_required to intercept:
@api. Route ('/post_apply ') @access_requireddef apply (): "" "," "" "" "" "" Print "is: ' +g.user return jsonify (res Ponse_data)
The implementation is simple:
# Verify Access_token and save current user to G def access_required (f): @wraps (f) def decorated_func (*args, **kwargs): access_ Token = request.values.get (' Access_token ') if Access_token == none: return error_msg (', ' access_token required ') if access_token == "": Return error_msg (', ' access_token can not empty ') if is_access_token (Access_token) == False: return error_msg (', ' Invalid_access_token ') &nbsP; return f (*args, **kwargs) return decorated_func
in Java , a custom annotation interceptor is implemented to add an annotation to the required interception method @accessrequired
Examples of usages in the Spring MVC controller
/** * Annotation Blocker method * @return */@RequestMapping (value= "/urlinter", Method=requestmethod.get) @AccessRequiredpublic @ Responsebody String urlinterceptortest () {return "via Interceptor: User" +request.getattribute ("Curruser");}
How to implement the above example?
Define an annotation:
Import Java.lang.annotation.elementtype;import Java.lang.annotation.retentionpolicy;import Java.lang.annotation.target;import java.lang.annotation.Retention; @Target (Elementtype.method) @Retention ( retentionpolicy.runtime) public @interface accessrequired {}
Engage an Interceptor:
In the spring MVC configuration file:
<!--Interceptor--><mvc:interceptors><mvc:interceptor><!--for all request interception using/**, for blocking requests under a module:/mypath/*-- ><mvc:mapping path= "/**"/><ref bean= "Useraccessinterceptor"/></MVC:INTERCEPTOR></MVC: Interceptors><bean id= "Useraccessinterceptor" class= " Com.banmacoffee.web.interceptor.UserAccessApiInterceptor "></bean>
When you're done, you can do whatever you want in the interceptor, and load it up any way you like the controller request.