记SpringSecurity的配置(SpringBoot)

本篇博客仅记录,为了方便以后的复习,如果有错误,还请博友指出
新建一个config包,放置各种配置
新建SecurityConfig配置类

package com.drc.config;


import org.springframework.beans.factory.annotation.Autowired;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;


@Configuration
public class SecurityConfigTest1 extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private DataSource dataSource;  // 注入数据源

    // 配置对象,这个是配置自动登录
    @Bean
    public PersistentTokenRepository tokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }


    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().accessDeniedPage("/unauth.html");  // 自定义403页面
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();
        http.formLogin()    // 自定义自己编写的登录界面
                .loginPage("/login.html")    // 登录页面设置
                .loginProcessingUrl("/user/login")  // 登录访问路径(有一个就行,这个逻辑不需要我们做,SpringSecurity帮我们做)
                .defaultSuccessUrl("/success.html").permitAll()   // 登录成功后,跳转的路径
                .and().authorizeRequests()
                    .antMatchers("/","/test/hello","/user/login").permitAll()   // 设置哪些路径可以直接访问,不需要认证
                .antMatchers("/test/index").hasAnyAuthority("admin")
                .anyRequest().authenticated()
                .and().rememberMe().tokenRepository(tokenRepository())
                .tokenValiditySeconds(60)   // 设置token时长
                .userDetailsService(userDetailsService) // 调用service操作数据库
                .and().csrf().disable();    // 关闭csrf的防护

    }
}


mapper层代码

package com.drc.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.drc.bean.Users;
import org.springframework.stereotype.Repository;


@Repository   // 继承了mybatisplus里面的BaseMapper
public interface UserMapper extends BaseMapper<Users> {
}

service层代码

package com.drc.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.drc.bean.Users;
import com.drc.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 使用的是MybatisPlus
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Users users = userMapper.selectOne(wrapper);
        if (users == null) {
            throw new UsernameNotFoundException("用户名不存在,请输入正确的用户名");
        }
        
        // 角色的添加
        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("admins");

        return new User(users.getUsername(),
                new BCryptPasswordEncoder().encode(users.getPassword()),
                role);
    }
}


html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/user/login" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    记住我:<input type="checkbox" name="remember-me"><br><!-- name必须为remember-me -->
    <input type="submit" value="登录" >
</form>
</body>
</html>

文章结束,为了方便以后的复习,写了这篇博客,如有错误,请大家指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值