Project summary of the second--login certification

Source: Internet
Author: User

First, Introduction


Traditional software, a single architecture, login authentication is relatively simple, basically through the session to achieve , that is, by all the incoming URI parsing, and get the user information in the current session . And the Internet software, architecture complex, need to deploy more than one machine, session is not unique, writing session will have a variety of problems, so we use to write a cookie way to authenticate.

In this project, we use the SPRINGMVC interceptor and login note certification, token of the way to login certification.


Second, the login certification process

1, user input user name, password to log in.

2, through the MVC Access background login method, than the database (or cache) in the user name and password is consistent.

3, if consistent, according to the user information generated a unique token (can use the user's information for several times md5+uid).

4, the generated token into the user's cookie, returned to the user.

5, when the user access to the relevant functions, to determine whether the action added login authentication annotations, if the addition of the note will need to be token verification through the interceptor, if the token in the cookie and the real-time generated tokens consistent, then put CurrentUser into the request, Otherwise, do not put.

6, in the action to obtain the value of CurrentUser, login authentication and the use of relevant parameters.


Iii. Development Examples (core code)


1, login.jsp

<formid="Login_form"action=".. /account/login "method="POST">
<ulclass="Form">
<li><inputtype="Text" placeholder="Account"name="UID"value="$!UID"/></li>
<li><inputtype="Password" placeholder="Password"name="Password"value="$!Password"/></li>
<li><ahref="#" class="BTN"onclick="Document.getElementById(' Login_form ').Submit();return False">Login</a></li>
</ul>
<divclass="Login_failure">$!Error</div>
</form>



2, authrequired (Login certification notes)

@Inherited
@Target (Elementtype.method)
@Retention (Retentionpolicy.runtime)
Public @interface authrequired {
}

3, Authhandlerinterceptor (Login authentication Interceptor)

@Component("Authhandlerinterceptor")
public class Authhandlerinterceptor implements Handlerinterceptor {
@Resource
Private UserService UserService;

@Override
public boolean prehandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object Handler) throws Exception {
if (Handler.getclass (). IsAssignableFrom (Handlermethod.class)) {
Authrequired authrequired = ((Handlermethod) handler). Getmethodannotation (Authrequired.class);
if (authrequired = = null) {
return true;
}
Cookie to get token
cookie[] cookies = httpservletrequest.getcookies ();
String token = "";

if (cookie = null) {
for (Cookie cookie:cookies) {
if (Cookie.getname (). Equals ("token")) {
token = Cookie.getvalue ();
}
}
}

if (null! = Token &&! "). Equals (token) && Token.contains ("_")) {
int id = integer.parseint (Token.split ("_") [0]);
String code = "";

User user = Userservice.getuser (ID);
if (null! = user && User.getlock () = = 0) {
Code = userservice.generatelogintoken (user);
}

if (code.equals (token)) {
Httpservletrequest.setattribute ("CurrentUser", user);
} else {
Httpservletresponse.sendredirect ("/account/login");
return false;
}
} else {
Httpservletresponse.sendredirect ("/account/login");
return false;
}
}

return true;
}

@Override
public void Posthandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, Modelandview Modelandview) throws Exception {
if (Httpservletrequest.getattribute ("CurrentUser")! = NULL && null! = Modelandview) {
Modelandview.addobject ("Current", Httpservletrequest.getattribute ("CurrentUser"));
}
}

@Override
public void Aftercompletion (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, Exception e) throws Exception {

}
}

4. Login action

@RequestMapping(value="/login", Method= Requestmethod.POST)
PublicStringLogin(String UID,
String Password,
Model model,
HttpServletResponse response) {
Try{
if(StringUtils.IsBlank(UID)) {
throw Newruntimeexception("account must be filled in");
}
if(StringUtils.IsBlank(password) | | Password.length () <6) {
throw Newruntimeexception("Password required and at least 6 bits");
}

User Userbyuid = userService. Getuserbyuid (UID);
If(Userbyuid = =NULL) {
throw Newruntimeexception("account does not exist");
}
Userbyuid =null;
User User =UserService. Login (UID, Password;
If(User = =NULL) {
throw Newruntimeexception("Incorrect account or password");
}

String token =UserService. Generatelogintoken (user);
Cookie cookie =NewCookies ("token", Token;
Cookie.setpath ("/");
Response.addcookie (Cookie);

Return"Redirect:/user/main";
}Catch(Exception e) {
Logger. Error ("Error", E;
Model.addattribute ("Error", E.getmessage ());
Model.addattribute ("UID", Uid;
Model.addattribute ("Password", Password;
Return"/account/login";
}
}

5 , need to log in to operate the action, there is @authrequired note that requires login interception, Only success can be related to the operation.


@AuthRequired
@RequestMapping (value = {"/main"}, method = {Requestmethod.get})
Public String GOMAINVM (@Value ("#{request.getattribute (' CurrentUser ')}") User Currentuser,model Model, HttpServletRequest request) throws Bizexception {
try {
if (null = = CurrentUser | | null = = Currentuser.getphone ()) {
throw new RuntimeException ("Please log in after Operation");
}

Post-Login Action ****************


return "/user/main";
} catch (Exception e) {
Logger.error ("error", e);
Model.addattribute ("Error", E.getmessage ());
return "/account/login";
}


}


6. Configuration Files

<beanclass= "Org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<beanclass= "Org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>
<MVC:interceptors>
<beanclass= "Com.happywork.interceptor.AuthHandlerInterceptor"/>
</MVC:interceptors>

At this point , login certification is completely done.


Iv. Performance Issues


Some people will ask, so often to read the database, whether it will bring a certain performance problems, here to do a brief explanation, this is only the function of the implementation of ideas, when the user volume up, directly from the cache, do not need to operate the database frequently, so that the frequent operation of the IO bottleneck.

This article is from the "Yao Sea" blog, please be sure to keep this source http://tl2011.blog.51cto.com/6006611/1787073

Project summary of the second--login certification

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.