当前位置:   article > 正文

springsecurity入门1-登陆角色验证_@loginsecurity

@loginsecurity

案例程序下载地址:https://github.com/snowlavenderlove/springsecurity.git

1.创建数据库springsecurity,并创建三张表,sys_user,sys_role,sys_user_role,并插入记录,图如下:

 2.创建项目springsecurityUserRole,创建时添加web、thymeleaf、jpa、security、mysql、mybatis框架,创建项目参考博文:https://blog.csdn.net/qq_37231511/article/details/90669242

3.在pom.xml中添加druid、logging依赖

  1. <dependency>
  2. <groupId>commons-logging</groupId>
  3. <artifactId>commons-logging</artifactId>
  4. <version>1.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>druid</artifactId>
  9. <version>1.1.17</version>
  10. </dependency>

4.编辑application.properties

  1. #mysql
  2. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springsecurity
  3. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  4. spring.datasource.username=root
  5. spring.datasource.password=123456
  6. #druid
  7. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  8. #mybatis
  9. mybatis.type-aliases-package=com.xue.repository.dao
  10. mybatis.mapper-locations=classpath*:com/xue/repository/mapper/*.xml

5.通过mybatis-generator自动生成代码,参考博文:https://blog.csdn.net/qq_37231511/article/details/90692784,自动生成后如图:

 

6.创建service层,创建SysUserService、SysRoleService、SysUserRoleService,代码如图

SysUserService

  1. package com.xue.service;
  2. import com.xue.entity.model.SysUser;
  3. public interface SysUserService {
  4. public SysUser selectUserByName(String username);
  5. public SysUser selectUserById(Integer id);
  6. }

SysRoleService 

  1. package com.xue.service;
  2. import com.xue.entity.model.SysRole;
  3. public interface SysRoleService {
  4. public SysRole selectRoleById(Integer id);
  5. }

SysUserRoleService 

  1. package com.xue.service;
  2. import java.util.List;
  3. import com.xue.entity.model.SysUserRole;
  4. public interface SysUserRoleService {
  5. public List<SysUserRole> selectUserRoleByUserId(Integer userId);
  6. }

7.创建Service层实现包:Impl,并创建SysUserServiceImpl、SysRoleServiceImpl、SysUserRoleServiceImpl,代码如下:

SysUserServiceImpl

  1. package com.xue.service.Impl;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;
  4. import com.xue.entity.model.SysUser;
  5. import com.xue.repository.dao.SysUserMapper;
  6. import com.xue.service.SysUserService;
  7. @Service
  8. public class SysUserServiceImpl implements SysUserService {
  9. @Autowired
  10. private SysUserMapper sysUserMapper;
  11. @Override
  12. public SysUser selectUserByName(String username) {
  13. // TODO Auto-generated method stub
  14. return sysUserMapper.selectUserByName(username);
  15. }
  16. @Override
  17. public SysUser selectUserById(Integer id) {
  18. // TODO Auto-generated method stub
  19. return sysUserMapper.selectUserById(id);
  20. }
  21. }

 SysRoleServiceImpl

 

  1. package com.xue.service.Impl;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;
  4. import com.xue.entity.model.SysRole;
  5. import com.xue.repository.dao.SysRoleMapper;
  6. @Service
  7. public class SysRoleServiceImpl implements com.xue.service.SysRoleService {
  8. @Autowired
  9. private SysRoleMapper sysRoleMapper;
  10. @Override
  11. public SysRole selectRoleById(Integer id) {
  12. // TODO Auto-generated method stub
  13. return sysRoleMapper.selectRoleById(id);
  14. }
  15. }

SysUserRoleServiceImpl

  1. package com.xue.service.Impl;
  2. import java.util.List;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. import com.xue.entity.model.SysUserRole;
  6. import com.xue.repository.dao.SysUserRoleMapper;
  7. import com.xue.service.SysUserRoleService;
  8. @Service
  9. public class SysUserRoleServiceImpl implements SysUserRoleService {
  10. @Autowired
  11. private SysUserRoleMapper sysUserRoleMapper;
  12. @Override
  13. public List<SysUserRole> selectUserRoleByUserId(Integer userId) {
  14. // TODO Auto-generated method stub
  15. return sysUserRoleMapper.selectUserRoleByUserId(userId);
  16. }
  17. }

 8.编辑dao层,编辑SysUserMapper、SysRoleMapper、SysUserRoleMapper文件

SysUserMapper:在最后添加

  1. SysUser selectUserByName(String username);
  2. SysUser selectUserById(Integer id);

SysRoleMapper:在最后添加

    SysRole selectRoleById(Integer id);

SysUserRoleMapper:在最后添加

    List<SysUserRole> selectUserRoleByUserId(Integer userId);

9.编辑mapper,编辑SysUserMapper、SysRoleMapper、SysUserRoleMapper

SysUserMapper:在最后添加

  1. <select id="selectUserById">
  2. select * from sys_user where id = #{id}
  3. </select>

SysRoleMapper:在最后添加

  1. <select id="selectRoleById" resultMap="BaseResultMap">
  2. select * from sys_role where id = #{id}
  3. </select>

SysUserRoleMapper:在最后添加

  1. <select id="selectUserRoleByUserId" resultMap="BaseResultMap">
  2. select * from sys_user_role where user_id =#{userId}
  3. </select>

10.在src/main/resources/templates下创建home.html与login.html

home.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>首页</title>
  6. </head>
  7. <body>
  8. <h1>登陆成功</h1>
  9. <a href="/admin">拥有admin权限</a>
  10. <a href="/user">拥有user权限</a>
  11. <button onclick="window.location.href='/logout'">退出</button>
  12. </body>
  13. </html>

login.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <h1 align="left">登陆</h1>
  9. <form action="/login" method="post">
  10. 用户名:<input type="text" name="username"/>
  11. 密码:<input type="password" name="password" />
  12. <button type="submit">登陆</button>
  13. </form>
  14. </body>
  15. </html>

11.创建Controller层,创建类LoginSecurityController

  1. package com.xue.controller;
  2. import org.springframework.security.access.prepost.PreAuthorize;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. @Controller
  7. public class LoginSecurityController {
  8. @RequestMapping("/")
  9. public String index(){
  10. return "home";
  11. }
  12. @RequestMapping("/login")
  13. public String login(){
  14. return "login";
  15. }
  16. /**
  17. * @PreAuthorize作用:判断用户是否有指定权限,没有就不能访问
  18. */
  19. @RequestMapping("/admin")
  20. @ResponseBody
  21. @PreAuthorize("hasRole('ROLE_ADMIN')")
  22. public String admin(){
  23. return "此权限为admin所有!";
  24. }
  25. @RequestMapping("/user")
  26. @ResponseBody
  27. @PreAuthorize("hasRole('ROLE_USER')")
  28. public String user(){
  29. return "此权限为user所有!";
  30. }
  31. }

 12.创建security层,创建CustomUserDetailsService,WebSecurityConfig

CustomUserDetailsService

  1. package com.xue.security;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.List;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.security.core.GrantedAuthority;
  7. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  8. import org.springframework.security.core.userdetails.User;
  9. import org.springframework.security.core.userdetails.UserDetails;
  10. import org.springframework.security.core.userdetails.UserDetailsService;
  11. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  12. import org.springframework.stereotype.Service;
  13. import com.xue.entity.model.SysRole;
  14. import com.xue.entity.model.SysUser;
  15. import com.xue.entity.model.SysUserRole;
  16. import com.xue.service.SysRoleService;
  17. import com.xue.service.SysUserRoleService;
  18. import com.xue.service.SysUserService;
  19. @Service
  20. public class CustomUserDetailsService implements UserDetailsService {
  21. @Autowired
  22. private SysUserService sysUserService;
  23. @Autowired
  24. private SysRoleService sysRoleService;
  25. @Autowired
  26. private SysUserRoleService sysUserRoleService;
  27. @Override
  28. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  29. // TODO Auto-generated method stub
  30. Collection<GrantedAuthority> authorities = new ArrayList<>();
  31. //从数据库user表中查询登陆者用户信息
  32. SysUser user = sysUserService.selectUserByName(username);
  33. if(null == user){
  34. throw new UsernameNotFoundException("用户不存在");
  35. }
  36. //从数据库sys_user_role表中查询登陆者所对应的用户权限关联信息
  37. List<SysUserRole> userRoleList = sysUserRoleService.selectUserRoleByUserId(user.getId());
  38. for(SysUserRole datas:userRoleList){
  39. //根据用户权限关联信息表中的权限id,从数据库sys_role表中查询登陆者所对应权限
  40. SysRole role = sysRoleService.selectRoleById(datas.getRoleId());
  41. authorities.add(new SimpleGrantedAuthority(role.getName()));
  42. }
  43. return new User(user.getUsername(),user.getPassword(),authorities);
  44. }
  45. }

WebSecurityConfig

  1. package com.xue.security;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  5. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  6. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  7. import org.springframework.security.config.annotation.web.builders.WebSecurity;
  8. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  9. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  10. import org.springframework.security.crypto.password.PasswordEncoder;
  11. @Configuration
  12. @EnableWebSecurity
  13. @EnableGlobalMethodSecurity(prePostEnabled=true)
  14. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  15. @Autowired
  16. private CustomUserDetailsService customUserDetailsService;
  17. @Override
  18. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  19. // TODO Auto-generated method stub
  20. /**
  21. * 密码的加密方式
  22. */
  23. auth.userDetailsService(customUserDetailsService).passwordEncoder(new PasswordEncoder() {
  24. @Override
  25. public String encode(CharSequence charSequence) {
  26. return charSequence.toString();
  27. }
  28. @Override
  29. public boolean matches(CharSequence charSequence, String s) {
  30. return s.equals(charSequence.toString());
  31. }
  32. });
  33. }
  34. @Override
  35. protected void configure(HttpSecurity http) throws Exception {
  36. // TODO Auto-generated method stub
  37. /**
  38. * .anyRequest().authenticated():设置所有请求都需通过认证才能访问
  39. * .and():表示一个配置的结束
  40. * .formLogin().loginPage("/login"):设置登陆页,loginPage中是对应controller中的登陆RequestMapping
  41. * .defaultSuccessUrl("/").permitAll():设置登陆成功页
  42. */
  43. http.authorizeRequests()
  44. .anyRequest().authenticated()
  45. .and()
  46. .formLogin().loginPage("/login")
  47. .defaultSuccessUrl("/").permitAll()
  48. .and()
  49. .logout().permitAll();
  50. /**
  51. * 关闭csrf
  52. */
  53. http.csrf().disable();
  54. }
  55. @Override
  56. public void configure(WebSecurity web) throws Exception {
  57. // TODO Auto-generated method stub
  58. }
  59. }

13.编辑主程序类SpringsecurityUserRoleApplication

  1. package com.xue;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @SpringBootApplication
  6. @MapperScan("com.xue.repository.dao")
  7. public class SpringsecurityUserRoleApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(SpringsecurityUserRoleApplication.class, args);
  10. }
  11. }

14.综上代码结构如图:

15.启动程序,在浏览器输入http://localhost:8080/login,用账号a密码123456登陆,登陆成功后如图

 16.点击拥有admin权限文字链接,没有权限则报错403

17. 点击拥有user权限文字链接,如图拥有权限

18.用admin账号登陆,则没有user权限

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/714016
推荐阅读
  

闽ICP备14008679号