Spring Security realizes login and privilege role Control _mssql2008

Source: Internet
Author: User
Tags auth prepare

Introduction to Essays

1, Spring version: 4.3.2.release+spring Security Version: 4.1.2.RELEASE (others do not explain)
2, all the display content with the annotation configuration
3, SPRINGMVC has been configured, not to explain
4, will involve springmvc,spel,el things, unfamiliar students can first look at this aspect of content, especially SPRINGMVC

First think about, landing needs what, the simplest case, username, password, and then compared to the database, if the match to jump to the personal page, otherwise return to the landing page, and prompts the user name password error. The process should also have permission roles, and throughout the session. With this in mind, we just need to give the database username password to spring security, and then let the security do the related jump, and let security help us to put the privilege role and username throughout the session, in fact, we just have to provide the correct username and password, and configure the security.

Directory

Preparatory work
Landing page
Personal page
Start configuring Spring Security

1. Start Spring Security

2. Configure permissions

3. Preparation of Userdetailservice

Prepare database Tables First

CREATE TABLE ' user ' (
 ' username ' varchar (255) NOT NULL,
 ' password ' char (255) isn't null,
 ' roles ' enum (' member ' , ' Member,leader ', ' super_admin ') not NULL DEFAULT ' member ',
 PRIMARY key (' username '),
 key ' username ' (' username ')
engine=innodb DEFAULT Charset=utf8;

PS: Note Here is the content of the roles, leader is also member, in this way, leader has the rights of member, of course, you can also make judgments in the application, which will be said later.

Landing Page

<%@ page contenttype= "Text/html;charset=utf-8" language= "Java" iselignored= "false"%> "<%@ taglib prefix=" C " Uri= "Http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix= "SF uri=" http://www.springframework.org/tags/  Form "%>  

personal page

<%@ page contenttype= "Text/html;charset=utf-8" language= "Java" iselignored= "false"%> <% @taglib prefix= " Security "uri=" Http://www.springframework.org/security/tags "%> <%@ taglib prefix=" SF "uri=" http:// Www.springframework.org/tags/form "%> 
@Order (2) Public
class Websecurityappinit extends abstractsecuritywebapplicationinitializer{
}

Inheriting abstractsecuritywebapplicationinitializer,spring security will automatically prepare for the work here @order (2) is before I springmvc (also a pure annotation configuration) and spring Security with the start of an error, specifically what I forget, add this let security startup in the after, you can avoid this problem, if not write @order (2) There is no fault without the tube.

2. Configure permissions

@Configuration @EnableWebSecurity @ComponentScan ("com.chuanzhi.workspace.service.impl.*") public class Websecurityconfig extends websecurityconfigureradapter{@Autowired private Userdetailservice Userdetailservic  E 
  If Userdetailservice is not scanned, add the above @componentscan @Override protected void Configure (Httpsecurity http) throws Exception { Http.authorizerequests (). Antmatchers ("/me"). Hasanyrole ("member", "super_admin")//Personal home page only allow Menber,super_ Admin role user access. Anyrequest (). authenticated (). and (). Formlogin (). LoginPage ("/"). Permitall ()//mileage The default path is the landing page, which allows all people to log in. Loginprocessingurl ("/log")//Login submitted processing URL. Failureforwardurl ("/?error=true")//Login Failure to forward, here back to the landing page, parameter error can inform the landing status. Defaultsuccessurl ("/me")//landing the successful URL, here goes to the personal home page. and (). Logout (). Logout URL ("/logout"). Permitall (). Logoutsuccessurl ("/?logout=true")//In order, the first is logged out of the url,security will intercept this URL for processing, so logout does not need us to implement,
     The second is to log out url,logout to inform the login status. and (). RememberMe (). Tokenvalidityseconds (604800)//Remember my function, the cookies have a deadline of one week. Remembermeparameter ("Remember-me")//when landing is activated remember the parameter name of my function, in landing   The page has a display. Remembermecookiename ("Workspace"); The name of the cookie, which can be viewed via the browser after login to the cookie name} @Override public void Configure (Websecurity Web) throws Exception {Super.confi
 Gure (web); @Override protected void Configure (Authenticationmanagerbuilder auth) throws Exception {Auth.userdetailsservice (US  Erdetailservice);

 Configure Custom Userdetailservice}}

3. Preparation of Userdetailservice

Spring Security provides us with the service to obtain user information, mainly to provide security to verify the user's information, here we can customize their own needs, I this is based on username from the database to get the user information, and give it to security for follow-up.

@Service (value = "Userdetailservice") public class Userdetailservice implements Userdetailsservice {@Autowired privat          

 e userrepository repository;              Public Userdetailservice (Userrepository userrepository) {this.repository = userrepository;  User warehouse, not described here} public userdetails Loaduserbyusername (String username) throws usernamenotfoundexception {User User
  = Repository.finduserbyusername (username); if (user==null) throw new Usernamenotfoundexception ("The account information is not found!")          ");      Throws an exception and jumps to the login failure page based on configuration list<grantedauthority> List = new arraylist<grantedauthority> ();              Grantedauthority is a security-provided permission class, GetRoles (User,list); Get the character, put it in the list org.springframework.security.core.userdetails.User auth_user = new Org.springframework.security.cor      E.userdetails.user (User.getusername (), User.getpassword (), list);
 Returns the user who includes the permission role to the security return auth_user; /** * Get the role * @param user * @param list */public void GEtroles (User user,list<grantedauthority> List) {for (String role:user.getRoles (). Split (",")) {List.add (new Sim          Plegrantedauthority ("Role_" +role));
 Permissions if the prefix is role_,security it is considered a role information, not a permission, for example Role_menber is the menber role, Can_send is the Can_send permission}}

If you want to remember my function effectively, the next time you enter the landing page to jump directly to the personal homepage You can look at this controller code

/** *
  Login page *
  @param
  * @return
 /@RequestMapping (value = "/") Public
 String Login (model model, User User
   , @RequestParam (value = "error", Required = False) Boolean error
   , @RequestParam (value = "Logout", Required = False) Boolean Logout,httpservletrequest request) {
  model.addattribute (user);
  If already landing jump to personal home
  authentication authentication = Securitycontextholder.getcontext (). Getauthentication ();
  if (authentication!=null&&
    !authentication.getprincipal (). Equals ("Anonymoususer") &&
    Authentication.isauthenticated ()) return
   "Me";
  if (error==true)
   model.addattribute ("error", error);
  if (logout==true)
   model.addattribute ("logout", logout);
  return "Login";
 

Results show:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.