Spring Security

2021-03-02 22:28

阅读:622

标签:runner   handle   namespace   demo   lse   create   java   ssr   rri   

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


dependency>
    groupId>org.springframework.bootgroupId>
    artifactId>spring-boot-starter-securityartifactId>
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


org.mybatis.spring.boot
    mybatis-spring-boot-starter
    2.1.0

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


mysql
    mysql-connector-java
    5.1.47

配置数据源

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


dependency>
    groupId>org.thymeleaf.extrasgroupId>
    artifactId>thymeleaf-extras-springsecurity5artifactId>
    version>3.0.4.RELEASEversion>
dependency>

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


dependency>
    groupId>org.springframework.bootgroupId>
    artifactId>spring-boot-starter-thymeleafartifactId>
    version>2.3.4.RELEASEversion>
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

标签:runner   handle   namespace   demo   lse   create   java   ssr   rri   

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


评论


亲,登录后才可以留言!