App login Java background processing and user rights verification

Source: Internet
Author: User
Tags md5 encryption

Recently do an app project, backstage I developed alone, the development of the task sequence is not placed on the login, registration and authorization to verify these basic functions in the first phase of development, is now part of the business related functions have been completed, but the user portal has not yet, can only explain the initial demand analysis is too anxious, Put the most basic user entrance to the back.

Now you need to add the user login and permission verification functionality based on the existing code.

For login and permission verification, refer to the previous development experience of iOS, the app side provides user name and password in exchange for token, each time in exchange for token request requires permission to log on the operation.

Now in turn, I need to consider the following questions:

1. How to easily meet the implementation of these functions in the code of the existing functions, making the existing code changes little, and the new features in the future to implement permission validation is not cumbersome

2. How to generate tokens based on user name and password, and how to differentiate the client from providing token correctness in the function requiring permission

First of all, according to the experience, the conventional solution is the filter, interceptors, if the requirements of the landing and authorization to verify these in front, as long as the post-function URL has a certain regularity, the use of filters or interceptors is almost always. But I am now faced with no previous design and specification of the URL, so the use of filters or interceptors I do not want to face.

In addition to the conventional solutions above, spring AOP is a powerful tool to solve these problems, using face slicing programming to make a pre-notification to all methods that require permission validation, but because URLs, class names, or methods are not regular, I think of custom annotations (annotation), Do permission validation on all method that adds custom annotations.

1. Now that you have thought of using spring AOP, the first step is to open the AOP in the spring configuration file

Open AOP

<aop:aspectj-autoproxy/>

The above configuration is based on pouring SPRING-AOP related jar packages into the project and introducing AOP URLs in the header of the configuration file

2. Next we define a custom annotation

@Target ({elementtype.method, elementtype.type})

@Retention (Retentionpolicy.runtime)

Public @interface UserAccess {

}

3. We are not yet in a hurry to do permission verification because our token has not yet generated a scenario.

The token generation is considered a single sign-on, so token cannot be fixed, otherwise at any time, as long as the token can be at least two people with the same account, which is currently not allowed in our business. Finally I chose "Username+password+ logon Time" to do MD5 encryption as token (there are many methods, such as UUID, in the case of guaranteed uniqueness and variability). Tokens are generated when the user name and password are verified successfully, and tokens are saved as key-value pairs of "Username:token" and "Token: User" (which can also be saved into the database), and then tokens are returned to the client.

The following code only makes one simple example:

@Service

public class Loginservice {

/**

* Store "Username: Token" key value pair

*/

public static map<string,string> tokenmap=new hashmap<string,string> ();

/**

* Store "Token:user" key value pairs

*/

public static map<string,user> loginusermap=new hashmap<string,user> ();

public string Login (string name,string password) {

System.out.println (name+ "-----" +password);

/**

* Determine if login is successful

* 1. Login successful

* 1.1. Successfully generated the corresponding token and updated

* 1.2. Failure throws an exception

*/

String token=tokenmap.get (name);

User User=null;

if (token==null) {

User=new User ();

User.setname (name);

User.setpassword (password);

SYSTEM.OUT.PRINTLN ("New user Login");

}else{

User=loginusermap.get (token);

Loginusermap.remove (token);

SYSTEM.OUT.PRINTLN ("Update user login token");

}

TOKEN=MD5UTIL.MD5 (Name+password+new Date (). GetTime ());

Loginusermap.put (token, user);

Tokenmap.put (name, token);

System.out.println ("currently has" +tokenmap.size () + "user");

For (User u:loginusermap.values ()) {

System.out.println (U.getname () + ":" +u.getpassword ());

}

return token;

}

}

4. At the same time, our client receives token after landing, as long as the token is carried in all requests requiring permission to successfully obtain the response (recommended: For the convenience of app coding, token can be carried in the request header, the existing code does not need big changes, And there's no need to worry about tokens in the future. I randomly found a method to do the experiment:

@Controller

@RequestMapping ("/login")

public class Logincontroller {

@Autowired

Private Loginservice Loginservice;

@UserAccess

@RequestMapping (value= "/loginin", Method=requestmethod.get)

Public @ResponseBody String Login (HttpServletRequest request) {

String name=request.getparameter ("name");

String password=request.getparameter ("password");

String token=loginservice.login (name, password);

return token;

}

}

Note that the bold part is the custom annotation, the login function request parameter is impossible to have token, so no matter how many times the verification, it is impossible to pass, just do an example. @UserAccess add functions that require permission validation

5. Now the custom annotation is a good entry point

@Component

@Aspect

public class Permissionaspect {

Setting to customize annotation as a pointcut

@Before ("@annotation (com.example.chap01.annotation.UserAccess)")

public void Checkpermission (Joinpoint joinpoint) throws exception{

System.out.println ("Pre-notification");

//get Intercept request parameters

object[] args = Joinpoint.getargs ();

HttpServletRequest request= (HttpServletRequest) args[0];

String Token=request.getparameter ("token");

System.out.println ("Pre-Notification token:" +token);

User User=loginservice.loginusermap.get (token);

if (user==null) {

System.out.println ("Verification does not pass!") ");

throw new Exception ("no permission");

}

}

}

At this point, the login and permission verification functions are all complete.

Also attached to personal github above source: Https://github.com/zw201913/applogin.git

App login Java background processing and user rights 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.