赞
踩
流程不写了 自己spring官网学去 我也是没人嘻嘻嘻嘻~~~
话不多说直接发代码
工程目录
application.properties
- spring.datasource.url=jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=utf-8
- spring.datasource.username=root
- spring.datasource.password=
- spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
- logging.level.org.springframework.security=INFO
- spring.thymeleaf.cache=false
- #打印sql,方便调试
- mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
domain
- package com.securitydemo.security.domain;
-
- public class Msg {
- private String title;
- private String content;
- private String etraInfo;
-
- public Msg(String title, String content, String etraInfo) {
- super();
- this.title = title;
- this.content = content;
- this.etraInfo = etraInfo;
- }
- public String getTitle() {
- return title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
- public String getContent() {
- return content;
- }
- public void setContent(String content) {
- this.content = content;
- }
- public String getEtraInfo() {
- return etraInfo;
- }
- public void setEtraInfo(String etraInfo) {
- this.etraInfo = etraInfo;
- }
-
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- package com.securitydemo.security.domain;
-
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
-
- public class SysRole {
-
- private Long id;
- private Long userId;
- private String name;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public void setUserId(Long userId) {
- this.userId = userId;
- }
-
- public Long getUserId() {
-
- return userId;
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- package com.securitydemo.security.domain;
-
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.List;
-
- import javax.persistence.CascadeType;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.ManyToMany;
-
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.authority.SimpleGrantedAuthority;
- import org.springframework.security.core.userdetails.UserDetails;
-
-
- public class SysUser implements UserDetails { //1
-
- private static final long serialVersionUID = 1L;
-
- private Long id;
- private String username;
- private String password;
-
- private List<SysRole> roles;
-
- /**
- * 重写getAuthorities()方法
- * 将用户角色作为权限
- *
- * @return
- */
-
- @Override
- public Collection<? extends GrantedAuthority> getAuthorities() {
- List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
- List<SysRole> roles = this.getRoles();
- for (SysRole role : roles) {
- auths.add(new SimpleGrantedAuthority(role.getName()));
- }
- return auths;
- }
-
- @Override
- public boolean isAccountNonExpired() {
- return true;
- }
-
- @Override
- public boolean isAccountNonLocked() {
- return true;
- }
-
- @Override
- public boolean isCredentialsNonExpired() {
- return true;
- }
-
- @Override
- public boolean isEnabled() {
- return true;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- public List<SysRole> getRoles() {
- return roles;
- }
-
- public void setRoles(List<SysRole> roles) {
- this.roles = roles;
- }
-
-
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
service 层 获取用户信息和角色信息
- package com.securitydemo.security.service;
-
- import com.securitydemo.security.domain.SysRole;
- import org.apache.ibatis.annotations.Mapper;
- import org.apache.ibatis.annotations.Select;
-
- import java.util.List;
-
- /**
- * @author Micky
- * @Title: UserRoleMapper
- * @ProjectName security
- * @Description:
- * @date 2018/7/20下午6:16
- */
- @Mapper
- public interface UserRoleMapper {
- @Select("select * from sys_role where userId=#{id}")
- List<SysRole> getRoleByUser(Long id);
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- package com.securitydemo.security.service;
-
- import com.securitydemo.security.domain.SysUser;
- import org.apache.ibatis.annotations.Mapper;
- import org.apache.ibatis.annotations.Select;
- import org.springframework.stereotype.Component;
-
- /**
- * @author Micky
- * @Title: SysUserMapper
- * @ProjectName security
- * @Description:
- * @date 2018/7/20下午4:36
- */
- @Mapper
- @Component
- public interface SysUserMapper {
- @Select("select * from sys_user where username=#{username}")
- SysUser findByUsername(String username);
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
自定义实现UserDetailsService 接口
- package com.securitydemo.security.security;
-
- import com.securitydemo.security.domain.SysRole;
- import com.securitydemo.security.domain.SysUser;
- import com.securitydemo.security.service.SysUserMapper;
- import com.securitydemo.security.service.UserRoleMapper;
- import org.springframework.beans.factory.annotation.Autowired;
- 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 java.util.ArrayList;
- import java.util.List;
-
- /**
- * @author Micky
- * @Title: CustomUserService
- * @ProjectName security
- * @Description: 实现自定义UserDetailsService接口
- * @date 2018/7/20下午3:26
- */
- public class CustomUserService implements UserDetailsService {
- @Autowired
- private SysUserMapper sysUserRepository;
- @Autowired
- private UserRoleMapper userRoleService;
-
- @Override
- public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- SysUser user = sysUserRepository.findByUsername(username);
- if(user == null){
- throw new UsernameNotFoundException("用户名不存在");
- }
- List<SimpleGrantedAuthority> authorities = new ArrayList<>();
- //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
- List<SysRole> roles = userRoleService.getRoleByUser(user.getId());
- for(SysRole role:roles)
- {
- authorities.add(new SimpleGrantedAuthority(role.getName()));
- System.out.println(role.getName());
- }
- return new org.springframework.security.core.userdetails.User(user.getUsername(),
- user.getPassword(), authorities);
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
配置confing
- package com.securitydemo.security.cofing;
-
- import org.springframework.context.annotation.Configuration;
- import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
- import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
-
- /**
- * @author Micky
- * @Title: WebMvcConfig
- * @ProjectName security
- * @Description:
- * @date 2018/7/20下午4:02
- */
- @EnableWebSecurity
- @Configuration
- public class WebMvcConfig extends WebMvcConfigurerAdapter {
- /**
- * 访问login 跳转到login.html页面
- *
- * @param registry
- */
- @Override
- public void addViewControllers(ViewControllerRegistry registry) {
- registry.addViewController("/login").setViewName("login");
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- package com.securitydemo.security.cofing;
-
- import com.securitydemo.security.security.CustomUserService;
- import org.springframework.context.annotation.Bean;
- 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.builders.WebSecurity;
- import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
- import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
- import org.springframework.security.core.userdetails.UserDetailsService;
-
- /**
- * @author Micky
- * @Title: WebSecurityConfig
- * @ProjectName security
- * @Description:
- * @date 2018/7/20下午4:07
- */
- @Configuration
- @EnableWebSecurity
- public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
- /**
- * 注册CustomUserService的bean
- *
- * @return
- */
- @Bean
- UserDetailsService customUserService() { //2
- return new CustomUserService();
- }
-
- /**
- * 添加我们自定义的user UserDetails
- *
- * @param auth
- * @throws Exception
- */
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(customUserService()); //3
-
- }
-
- /**
- * @param http
- * @throws Exception
- */
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests()
- .anyRequest().authenticated() //4 所有请求必须要登录后才能认证
- .and()
- .formLogin()
- .loginPage("/login")
- .failureUrl("/login?error")//登录失败访问的页面
- .permitAll() //5 定制登录页面行为登录页面可以任意访问
- .and()
- .logout().permitAll() //6 注销可以任意访问
- .and().formLogin();
- http.csrf().disable();
-
-
- }
-
- @Override
- public void configure(WebSecurity web) throws Exception {
- super.configure(web);
- web.ignoring().antMatchers("/css/**", "/css/**", "/images/**");//静态资源访问
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
controller层
- package com.securitydemo.security.controller;
-
- import com.securitydemo.security.domain.Msg;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- /**
- * @author Micky
- * @Title: HomeController
- * @ProjectName security
- * @Description:
- * @date 2018/7/20下午4:22
- */
- @Controller
- public class HomeController {
- @RequestMapping("/")
- public String index(Model model) {
- Msg msg = new Msg("测试标题", "测试内容", "额外信息,只对管理员显示");
- model.addAttribute("msg", msg);
- return "home";
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
前端页面 thymeleaf为我们提供了spring security 的标签支持
通过 sec:authentication="name" 获取当前用户名
sec:authorize="hasRole('ROLE_USER')" 意味着只能是ROLE_USER才可以显示标签内容
sec:authorize="hasRole('ROLE_ADMIN')意味着只能是ROLE_ADMIN才可以显示标签内容
注销路径默认是/logout 必须要post 提交
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta content="text/html;charset=UTF-8"/>
- <title>登录页面</title>
- <link rel="stylesheet" th:href="@{css/bootstrap.min.css}"/>
- <style type="text/css">
- body {
- padding-top: 50px;
- }
- .starter-template {
- padding: 40px 15px;
- text-align: center;
- }
- </style>
- </head>
- <body>
-
- <nav class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <a class="navbar-brand" href="#">Spring Security演示</a>
- </div>
- <div id="navbar" class="collapse navbar-collapse">
- <ul class="nav navbar-nav">
- <li><a th:href="@{/}"> 首页 </a></li>
-
- </ul>
- </div><!--/.nav-collapse -->
- </div>
- </nav>
- <div class="container">
-
- <div class="starter-template">
- <p th:if="${param.logout}" class="bg-warning">已成功注销</p><!-- 1 -->
- <p th:if="${param.error}" class="bg-danger">有错误,请重试</p> <!-- 2 -->
- <h2>使用账号密码登录</h2>
- <form name="form" th:action="@{/login}" action="/login" method="POST"> <!-- 3 -->
- <div class="form-group">
- <label for="username">账号</label>
- <input type="text" class="form-control" name="username" value="" placeholder="账号" />
- </div>
- <div class="form-group">
- <label for="password">密码</label>
- <input type="password" class="form-control" name="password" placeholder="密码" />
- </div>
- <input type="submit" id="login" value="Login" class="btn btn-primary" />
- </form>
- </div>
-
- </div>
-
- </body>
- </html>
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org"
- xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"><!-- 1 -->
- <head>
- <meta content="text/html;charset=UTF-8"/>
- <title sec:authentication="name"></title> <!-- 2 -->
- <link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
- <style type="text/css">
- body {
- padding-top: 50px;
- }
- .starter-template {
- padding: 40px 15px;
- text-align: center;
- }
- </style>
- </head>
- <body>
- <nav class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <a class="navbar-brand" href="#">Spring Security演示</a>
- </div>
- <div id="navbar" class="collapse navbar-collapse">
- <ul class="nav navbar-nav">
- <li><a th:href="@{/}"> 首页 </a></li>
-
- </ul>
- </div><!--/.nav-collapse -->
- </div>
- </nav>
-
-
- <div class="container">
-
- <div class="starter-template">
- <h1 th:text="${msg.title}"></h1>
-
- <p class="bg-primary" th:text="${msg.content}"></p>
-
- <div sec:authorize="hasRole('ROLE_ADMIN')"> <!-- 3 -->
- <p class="bg-info" th:text="${msg.etraInfo}"></p>
- </div>
-
- <div sec:authorize="hasRole('ROLE_USER')"> <!-- 4-->
- <p class="bg-info">无更多信息显示</p>
- </div>
-
- <form th:action="@{/logout}" method="post">
- <input type="submit" class="btn btn-primary" value="注销"/><!-- 5 -->
- </form>
- </div>
-
- </div>
-
-
- </body>
- </html>
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
运行
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。