首页 > 编程语言 > 详细

Spring Security

时间:2021-02-15 09:37:58      阅读:34      评论:0      收藏:0      [点我收藏+]

Spring Security简介

技术分享图片

历史

技术分享图片

添加parent和web依赖

SpringBootApplication

@MapperScan
@SpringBootApplication
public class SpringSecurityApplication{ public static void main(String[] args){ SpringApplication.run(SpringSecurityApplication.class, args); } }

MyTest

SpringBootTest(classes = SpringSecurityApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class MyTest{
    @Test
    public void test(){
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String result = encoder.encode("pwd");
        System.out.println(result);
boolean match = encode.matches("pwd", result);
System.out.println(match); } }

DemoController

@Controller
public class DemoController{
    @RequestMapping("/");
    @ResponseBody
    public String demo(){
        return "demo";
    }
}

添加依赖,官方地址:https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

进入http://localhost:8080/login.html

UserDetailService详解

public interface UserDetailService{
    UserDetails loadUserByUserName(String var1) throws UsernameNotFoundException;
}

接口方法

技术分享图片

UserDetailServiceimpl

@Service
public class UserDetailsServiceImpl implements UserDetailsService{
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Overrride
    public UserDetails loadUserByUserName(String username) throws UsernameNotFoundException{
        if(!username.equals("admin")){
            throw new UsernameNotFoundException("用户不存在!");
        }
        // 从数据库中获取密码
        String password = "pwd";
        String encodePassword = PasswordEncoder.encode(password);
        UserDetails userDetails = new User(username, encodePassword, AuthorityUtils.commaSeparatedStringToAuthorityList("admin1, admin2"));
        return userDetails;
    }
}

SecurityConfig

@Configuration
public class SecurityConfig{
    @Bean
    protected PasswordEncoder passwrodEncoder(){
        return new BCryptPasswordEncoder();
    }    
}

连接数据库实现自定义逻辑

UserMapper

public interface UserMapper{
    public User selectByUserName(String username);
}

application.yml

spring:
    datasource:
        username: root
        password: root
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/test
mybatis:
    mapper-locations: classpath:mybatis/*.xml

UserMapper.xml

<mapper namespace="com.test.mapper.UserMapper">
    <select id="selectByUsername" resultType="com.test.pojo.User">
        select id, username, password from t_user where username = #{param}
    </select>
</mapper>

注解@Secured的使用

在启动类中添加注解

@EnaleGlobalMethodSecurity(securedEnabled = true)

在controller中添加注解

@Secured("ROLE_ADMIN")

ConfigureAdapter中添加

.antMatchers("/demo").permitAll()

技术分享图片

 

@PreAuthorize/@PostAuthorize

启动类

@EnaleGlobalMethodSecurity(prePostEnabled = true)

controller

@PreAuthorize("hasAuthority(‘demo:update‘)")

技术分享图片

Remember me功能实现

技术分享图片

添加mybatis依赖,官方地址:https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>

添加mysql依赖,官方地址:https://mvnrepository.com/artifact/mysql/mysql-connector-java

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

配置数据源

applicaiton.yml

spring:
    datasource:
        username: root
        password: root
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/test
mybatis:
    mapper-locations: classpath:mybatis/*.xml

RememberMeConfig

@Configuration
public class RemeberMeConfig{
    @Autowired
    private Datasource dataSource;
    @Bean
    protected PersonTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcToeknRepositoryImpl();
        jdbcTokenRepository.setCreateTableOnStartup(true);
        jdbcTokenRepository.setDataSource(dataSource);

        return jdbcTokenRepository;
    }
}

WebSecurityConfigureAdapter

@Autowire
private PersistentTokenRepository persistentTokenRepository;

修改SecurityConfig

http.rememberMe()
     .userDetailsSevice(userDetailsService)// 登录逻辑对象
     .tokenValiditySeconds(10)// 设置有效时间
     .tokenRepository(persistentTokenRepository);// 持久层对象

在客户端页面添加复选框

添加依赖,官方地址:https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5

<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

添加依赖,官方地址:https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.3.4.RELEASE</version>
</dependency>

获取属性

技术分享图片

退出登录

技术分享图片

MyWebSecurityconfigurerAdapter

http.logout()
      .logoutSuccessUrl("/showLogin")
      .logoutUrl("/test")
      .logoutSuccesshandler(new LogoutSuccessHandler(){
        @Override
        public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse httpServletResponse, Authentication authentication) throws Exception{}
    })

Spring Security中的CSRF详解

@SpringBootApplication
public class CsrfApplication{
    public static void main(STring[] args){
        SpringApplication.run(CsrfApplication.class, args);
    }
}

application.ymml

server:
    port: 8081
    

技术分享图片

 

Spring Security

原文:https://www.cnblogs.com/YC-L/p/14397571.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!