Spring Security

依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

新建配置类继承 WebSecurityConfigurerAdapter

  • 配置认证方式,重写 configure(AuthenticationManagerBuilder auth) 方法
  • 配置 http 请求 安全规则,重写 configure(HttpSecurity http) 方法
    • 请求授权‌:
      • 我们可以使用 authorizeRequests() 方法来定义哪些请求需要认证,哪些不需要。
      • 例如,我们可以指定某些URL路径允许所有用户访问(无需认证),而其他路径则需要用户具有特定的角色或权限才能访问。
    • 表单登录‌:
      • 使用 formLogin() 方法可以配置基于表单的登录。
      • 我们可以指定登录页面的URL、登录成功后的跳转页面,以及登录失败时的处理。
    • HTTP Basic认证‌:
      • 通过 httpBasic() 方法可以启用HTTP Basic认证,这通常用于简单的RESTful服务。
    • CSRF保护‌:
      • 使用 csrf() 方法可以启用或禁用CSRF(跨站请求伪造)保护。
    • 注销‌:
      • 使用 logout() 方法可以配置用户注销的功能,包括注销后的跳转页面。
    • 其他安全配置‌:
      • 我们还可以配置headers()、session()等来控制HTTP头的安全性和会话管理。
package com.shore.my_spring_demo.web.config;

import com.shore.my_spring_demo.dal.entity.UserEntity;
import com.shore.my_spring_demo.dal.repo.UserServiceRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;
import java.util.ArrayList;


@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserServiceRepo userServiceRepo;

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(username -> {
            UserEntity userEntity = userServiceRepo.getUserByUsername(username);
            if (userEntity == null) {
                throw new UsernameNotFoundException(String.format("User %s not found", username));
            }
            return new User(userEntity.getUsername(), userEntity.getPassword(), new ArrayList<>());
        })
        .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/", "/shore/demo/user/login", "/shore/demo/user/register").permitAll()
        .anyRequest().authenticated()
        .and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

用户注册

用户密码转为密文方式保存

@Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public boolean register(UserReq userAddReq) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(userAddReq.getUsername());
        userEntity.setPassword(passwordEncoder.encode(userAddReq.getPassword()));
        userEntity.setEmail(userAddReq.getEmail());
        userEntity.setPhone(userAddReq.getPhone());
        userEntity.setNickname(userAddReq.getNickname());
        userEntity.setAddress(userAddReq.getAddress());
        userEntity.setAge(userAddReq.getAge());
        return userServiceRepo.addUser(userEntity);
    }

用户登录

调用上面配置的认证方式进行身份认证

@PostMapping("/login")
    public String login(@RequestBody UserReq req) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPassword())
        );
        System.out.println(req);
        System.out.println(authentication);
        return "";
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值