springBoot+thymeleaf+security

springBoot+thymeleaf+security

1. maven版本

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.liyang</groupId>
    <artifactId>jd</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jd</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    </properties>

    <dependencies>
        <!--安全框架-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!--thymleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--bootstrap-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. security配置类

package cn.liyang.jd.config;


import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure (HttpSecurity http) throws Exception {
		//指定授权规则
		http.authorizeRequests().antMatchers( "/" ).permitAll()
				.antMatchers( "/admin/**" ).hasRole( "admin" )
				.antMatchers( "/user/**" ).hasRole( "user" )
				.antMatchers( "/vip/**" ).hasRole( "vip" );
		//开启自动配置的登录功能
		//loginPage()开启定制登录页面,并再controller中指定跳转的页面
		//"/userlogin"get请求代表请求登录页,post请求代表处理登录
		http.formLogin().loginPage( "/userlogin" );
		//开启自动注销功能,用户注销清空session,并设置退出成功后返回的页面,自定义退出路径,post提交
		http.logout().logoutSuccessUrl( "/out" );
		//记住我,关闭浏览后,重新打开不用登录,自定义页面时,设置checkbox 的neme值
		http.rememberMe().rememberMeParameter( "remeber" );
	}

	@Override
	protected void configure (AuthenticationManagerBuilder auth) throws Exception {
		//passwordEncoder设置加密类型,并且登录的时候会对登录密码先进行加密加盐然后再与正确的密码比较
		// new BCryptPasswordEncoder().encode( "admin" )对密码加密
		//设置用户的角色,可以多多个
		auth.inMemoryAuthentication().passwordEncoder( new BCryptPasswordEncoder() )
				.withUser("admin").password( new BCryptPasswordEncoder().encode( "admin" ) ).roles( "admin","vip","user" )
				.and()
				.withUser("vip").password( new BCryptPasswordEncoder().encode( "admin" ) ).roles( "vip","user" )
				.and()
				.withUser("user").password(new BCryptPasswordEncoder().encode( "admin" ) ).roles( "user" );
	}

	
}


3. 输入http://localhost:8080显示首页配置

http.authorizeRequests().antMatchers( "/" ).permitAll()
 @RequestMapping("/")
    public String shouye(){
        return "home";
    }
  • 首先开放"/"路径权限
  • 再controller层配置"/’'路径跳转,要设置的首页

4. 登录成功后显示用户信息和拥有的权限

  1. 现在html中导入sec的命名空间
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
  1. 回显信息

	<h1 align="center">欢迎登录!</h1>
	//如果是未登录的状态显示 请登录
    <div sec:authorize="!isAuthenticated()">
        <h1 align="center">游客你好,<a th:href="@{/userlogin}">请登录</a></h1>
    </div>
    //如果是已经登录显示用户信息和角色权限
    <div sec:authorize="isAuthenticated()">
        <h2 align="center">
            <span sec:authentication="name"></span>,你好,你的角色有
            <span sec:authentication="principal.authorities"></span>
            //这个版本,退出登录一定要用post用get会失败
            <form th:action="@{/logout}" method="post">
                <input type="submit" value="注销">
            </form>
        </h2>
    </div>

5. 不同的角色,用拥有不同的权限,显示不同的页面内容

 <div class="starter-template">
        <h1>Spring Boot + Thymeleaf + Spring Security 示例</h1>
        <div sec:authorize="hasRole('admin')">
            <h2>1. 打开 <a th:href="@{/admin}">管理员页面 (受 Spring Security 保护, 需要管理员权限)</a></h2>
        </div>
        <div sec:authorize="hasRole('user')">
            <h2>2. 打开 <a th:href="@{/user}">用户页面 (受 Spring Security 保护, 需要用户权限)</a></h2>
        </div>
        <div sec:authorize="hasRole('vip')">
            <h2>3. 打开 <a th:href="@{/vip}">vip页面</a></h2>
        </div>
    </div>

6. 记住我的功能,浏览器关闭后,下次访问网站直接登录的状态

	//记住我,关闭浏览后,重新打开不用登录
		http.rememberMe();
在这里插入代码片

7. 自定义登录页

	//开启自动配置的登录功能
		//loginPage()开启定制登录页面,并再controller中指定跳转的页面
		//"/userlogin"get请求代表请求登录页,post请求代表处理登录
		http.formLogin().loginPage( "/userlogin" );
  • 现在Congtroller中指定 “/userlogin” 要跳转的登录页
 @RequestMapping("/userlogin")
    public String login(){
        return "login";
    }
  • 在自定义的登录表单,用post请求,提交表单
<form style="margin-left:500px;margin-top:200px;" th:action="@{/userlogin}" method="post">
    <div class="form-group">
        <label for="user" stype="display:inline;">账户:</label>
        <input type="text" class="form-control" id="user" style="display:inline;width:200px;"autocomplete="off" name="username" />
    </div>
    <div class="form-group">
        <label for="password" style="display:inline;">密码:</label>
        <input type="text" class="form-control" id="password" style="display:inline;width:200px;"autocomplete="off" name="password" />
    </div>
    <button type="submit" class="btn btn-primary">登录</button>
    <button type="submit" class="btn btn-primary">注册</button>
</form>
  • 自定义登录参数name
http.formLogin().usernameParameter( "user" ).passwordParameter( "pwd" ).loginPage( "/userlogin" );

8. 自定义页面中设置remeber()

  • 配置类
	//记住我,关闭浏览后,重新打开不用登录,自定义页面时,设置checkbox 的neme值
		http.rememberMe().rememberMeParameter( "remeber" );
  • 登录页面form表单
 <input type="checkbox" name="remeber">记住我

9. 自定义Logou成功后跳转的路径

http.logout().logoutSuccessUrl( "/out" );
   @RequestMapping("/out")
    public String logout(){
        return "home";
    }

10. 从数据库查询用户

  • 实现security的implements UserDetailsService接口从写loadUserByUsername(String username) 方法
package cn.liyang.jd.service.impl;

import cn.liyang.jd.mapper.UserMapper;
import cn.liyang.jd.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;


/**
* @author liyang
* @date 2019/9/11 10:53
* @description:
*/
@Service
public class SecurityUserDetailsServiceImpl  implements UserDetailsService {
   // 用户查询接口
   @Autowired
   private UserMapper userMapper;




   @Override
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       System.out.println("come in");
       //根据用户名获取用户对象
       User users = userMapper.findByUserName( username );
       System.out.println(users);
       if (users != null) {
           //创建角色集合对象
           Collection<GrantedAuthority> authorities = new ArrayList<>();
           //如果有多个权限,数据库查出数组
           //创建临时角色对象
           GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_admin");
           //对象添加到集合中
           authorities.add(grantedAuthority);
           //参数"{noop}"+ sysUser.getPassword() 表示不使用加密登录
           //参数sysUser.getPassword() 表示使用密码登录
           org.springframework.security.core.userdetails.User user =new org.springframework.security.core.userdetails.User( users.getUsername(), users.getPassword(), authorities );
//            User user = new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
//            System.out.println("user:" + user);
          return user;
       }
       return null;
   }

}
  • 在配置类中开启从数据库查询用户登录功能
	@Autowired
	 SecurityUserDetailsServiceImpl userDetailsService;
@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth
				.userDetailsService(this.userDetailsService)
				.passwordEncoder(passwordEncoder());

	}
  • 注意:在配置类中设置角色"admin"后,框架会自动拼接成"ROLE_admin",在数据库中设置角色要写成"ROLE_XXX"
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值