Home  >  Article  >  类库下载  >  Use spring security to implement simple login and permission role control

Use spring security to implement simple login and permission role control

高洛峰
高洛峰Original
2016-10-17 09:08:482419browse

First think about what is needed to log in. In the simplest case, username and password, and then compare it with the database. If they match, jump to the personal page. Otherwise, return to the login page and prompt that the username and password are incorrect. This process should also have permission roles and continue throughout the entire session. With this idea, we only need to hand over the user name and password of the database to spring security for comparison, and then let security make relevant jumps, and let security help us put the permission roles and user names throughout the entire session. In fact, we only need Provide the correct username and password, and configure security.

Directory

Preparation

Login page

Personal page

Start configuring spring security

1. Start spring security

2. Configure permissions

3. Write UserDetailService

First prepare the database table

CREATE TABLE `user` (
  `username` varchar(255) NOT NULL,
  `password` char(255) NOT NULL,
  `roles` enum('MEMBER','MEMBER,LEADER','SUPER_ADMIN') NOT NULL DEFAULT 'MEMBER',
  PRIMARY KEY (`username`),
  KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

PS : What you should pay attention to here is the content of roles. LEADER is also a MEMBER. In this way, LEADER will have the permissions of MEMBER. Of course, you can also make judgments in the application, which will be mentioned later.

<%@ 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"%>
<html>
<head>
    <title>登录</title>
</head>
<body>
<div >
    
    <sf:form action="${pageContext.request.contextPath}/log" method="POST" commandName="user">     <!-- spring表单标签,用于模型绑定和自动添加隐藏的CSRF token标签 -->
        <h1 >登录</h1>
        <c:if test="${error==true}"><p style="color: red">错误的帐号或密码</p></c:if>      <!--  登陆失败会显示这句话 -->
        <c:if test="${logout==true}"><p >已退出登录</p></c:if>                    <!-- 退出登陆会显示这句话 -->
        <sf:input path="username" name="user.username"  placeholder="输入帐号" /><br />
        <sf:password path="password" name="user.password"  placeholder="输入密码" /><br />
        <input id="remember-me" name="remember-me" type="checkbox"/>                <!-- 是否记住我功能勾选框 -->
        <label for="remember-me">一周内记住我</label>
        <input type="submit" class="sumbit" value="提交" >
    </sf:form>
</div>
</body>
</html>

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"%>
<html>
<head>
    <title>欢迎你,<security:authentication property="principal.username" var="username"/>${username}</title>      <!--  登陆成功会显示名字,这里var保存用户名字到username变量,下面就可以通过EL获取 -->
</head>
<body>
<security:authorize access="isAuthenticated()"><h3>登录成功!${username}</h3></security:authorize>  <!--  登陆成功会显示名字 -->

<security:authorize access="hasRole(&#39;MEMBER&#39;)">              <!--  MENBER角色就会显示 security:authorize标签里的内容-->
    <p>你是MENBER</p>
</security:authorize>

<security:authorize access="hasRole(&#39;LEADER&#39;)">
    <p>你是LEADER</p>
</security:authorize>


<sf:form id="logoutForm" action="${pageContext.request.contextPath}/logout" method="post">      <!--  登出按钮,注意这里是post,get是会登出失败的 -->
    <a href="#" onclick="document.getElementById(&#39;logoutForm&#39;).submit();">注销</a>
</sf:form>
</body>
</html>

Start configuring spring security


Start spring security

@Order(2)public class WebSecurityAppInit extends AbstractSecurityWebApplicationInitializer{
}

Inheriting AbstractSecurityWebApplicationInitializer, spring security will automatically make preparations. Here @Order(2) is my springmvc (also a pure annotation configuration) An error occurred when starting with spring security. I forgot what it was. Adding this to start security later can avoid this problem. If there is nothing wrong with not writing @Order(2), don't worry about it.

  2. Configure permissions

@Configuration
@EnableWebSecurity
@ComponentScan("com.chuanzhi.workspace.service.impl.*")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{          

    @Autowired
    private UserDetailService userDetailService;                  //如果userDetailService没有扫描到就加上面的@ComponentScan

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                    .antMatchers("/me").hasAnyRole("MEMBER","SUPER_ADMIN")  //个人首页只允许拥有MENBER,SUPER_ADMIN角色的用户访问
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/").permitAll()                  //这里程序默认路径就是登陆页面,允许所有人进行登陆
                    .loginProcessingUrl("/log")                  //登陆提交的处理url
                    .failureForwardUrl("/?error=true")              //登陆失败进行转发,这里回到登陆页面,参数error可以告知登陆状态
                    .defaultSuccessUrl("/me")                    //登陆成功的url,这里去到个人首页
                    .and()
                .logout().logoutUrl("/logout").permitAll().logoutSuccessUrl("/?logout=true")    //按顺序,第一个是登出的url,security会拦截这个url进行处理,所以登出不需要我们实现,第二个是登出url,logout告知登陆状态
                    .and()
                .rememberMe()
                    .tokenValiditySeconds(604800)                //记住我功能,cookies有限期是一周
                    .rememberMeParameter("remember-me")              //登陆时是否激活记住我功能的参数名字,在登陆页面有展示
                    .rememberMeCookieName("workspace");            //cookies的名字,登陆后可以通过浏览器查看cookies名字
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService);                //配置自定义userDetailService
    }
}

3. Write UserDetailService

The Service that spring security provides us to obtain user information mainly provides security with information to verify users. Here we can customize our own needs. This is mine Obtain the user's information from the database according to the username, and then hand it over to security for subsequent processing

@Service(value = "userDetailService")
public class UserDetailService implements UserDetailsService {

    @Autowired
    private UserRepository repository;          

    public UserDetailService(UserRepository userRepository){
        this.repository = userRepository;              //用户仓库,这里不作说明了
    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = repository.findUserByUsername(username);
        if (user==null)
            throw new UsernameNotFoundException("找不到该账户信息!");          //抛出异常,会根据配置跳到登录失败页面

        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();      //GrantedAuthority是security提供的权限类,

        getRoles(user,list);              //获取角色,放到list里面

        org.springframework.security.core.userdetails.User auth_user = new
                org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);      //返回包括权限角色的User给security
        return auth_user;
    }

    /**
     * 获取所属角色
     * @param user
     * @param list
     */
    public void getRoles(User user,List<GrantedAuthority> list){
        for (String role:user.getRoles().split(",")) {
            list.add(new SimpleGrantedAuthority("ROLE_"+role));          //权限如果前缀是ROLE_,security就会认为这是个角色信息,而不是权限,例如ROLE_MENBER就是MENBER角色,CAN_SEND就是CAN_SEND权限
        }
    }
}

If you want to jump directly to the personal homepage when you enter the login page next time when the remember me function is effective, you can take a look at this controller code

/**
     * 登录页面
     * @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);
        //如果已经登陆跳转到个人首页
        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";
    }

Result display:

Use spring security to implement simple login and permission role control

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn