SpringSecurity入门及进阶:登录,记住登录,获取当前登录用户,修改密码

本文详细介绍了Spring Security的配置方法,包括如何通过配置文件启用Spring Security,配置用户认证和授权策略,以及如何在控制器中使用注解来限制访问权限。文章还展示了如何自定义用户详情服务,实现数据库中的用户信息加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置文件

package com.falun.conf;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

/**
 * Created by admin on 2019/9/2.
 */
@Configuration
@EnableWebSecurity //启用SpringSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true) //启用方法上的权限注解
//参考 https://docs.spring.io/spring-security/site/docs/5.0.2.RELEASE/reference/htmlsingle/
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    @Resource
    SecurityUserSvc securityUserSvc;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
//        从数据库查询用户名密码是否正确
        auth.userDetailsService(securityUserSvc)
            .passwordEncoder(new BCryptPasswordEncoder());
//        .and().jdbcAuthentication();;
//            .and().inMemoryAuthentication().withUser("mickael").password("zsr").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.authorizeRequests()
                .antMatchers("/manage/**").hasRole("ADMIN")
                .antMatchers("/buy/**").hasRole("USER")
                .antMatchers("/comment/**").hasRole("USER")
                .antMatchers("/**","/").permitAll()
//                .anyRequest().authenticated()
//                .anyRequest().anonymous()
//                .and()
//                .formLogin().loginPage("/login.html");
                .and()
                .httpBasic()
                .and()
                .logout().permitAll()
                .and()
                .rememberMe()//.alwaysRemember(true) //alwaysRemember这个配置会让页面上的是否记住勾选选项失效
                .tokenValiditySeconds(86400)//rememberMe for one day
                ;
        http.csrf().disable();//在原本的配置文件下添加这行代码,禁用security的csrf
        super.configure(http);
    }
}

用户详情服务

package com.falun.conf;

import com.falun.pojo.User;
import com.falun.pojo.UserRole;
import com.falun.repo.UserRepo;
import org.springframework.security.core.*;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by admin on 2019/9/2.
 */
@Service
public class SecurityUserSvc implements UserDetailsService {
    @Resource
    UserRepo userRepo;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User u= userRepo.getByName(s);
        List<GrantedAuthority> roles =new LinkedList<>();
        u.getUserRole().forEach((UserRole ur)->{
            roles.add(new SimpleGrantedAuthority(ur.getRole().toString()));});
        UserDetails userDetails= new org.springframework.security.core.userdetails.User(u.getName(),u.getPassword(),roles);
        return userDetails;
    }
}

项目中的使用

package com.falun.ctrl;

import com.falun.base.RespObj;
import com.falun.pojo.User;
import com.falun.pojo.UserRole;
import com.falun.repo.UserRepo;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by admin on 2019/8/20.
 */
@RestController
@RequestMapping("user")
@Validated
public class UserCtrl {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16);
    @Resource
    UserRepo userRepo;

    @RequestMapping("login")
    public Object login(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response){
        if(userRepo.login(user)){
//            request.getUserPrincipal()
//            response
//            request.authenticate(response);
//            response.
//            request.login(user.getName());
            return 1;
        }
        return 0;
    }

    @RequestMapping("reg")
    public Object reg(@ModelAttribute User user){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16);
        String result = encoder.encode(user.getPassword());
        user.setPassword(result);
        //给注册的角色添加默认的权限
        List<UserRole> userRoles=new LinkedList<>();
        UserRole userRole=new UserRole();
        userRole.setRole(UserRole.RoleName.USER);
        userRole.setUser(user);
        user.setUserRole(userRoles);
        return new RespObj( userRepo.save(user));
    }
//    org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver;
//    @Secured()
//    @PreAuthorize("! isAnonymous()")
    @PreAuthorize("authenticated")
//    @PreAuthorize("#user !=null")
    @RequestMapping("reset")
    public Object reset(String oldPassword,String newPassword,@AuthenticationPrincipal org.springframework.security.core.userdetails.User user){
        User u= userRepo.getByName(user.getUsername());
//        user获取不到密码,因为这个属性被设置成了透明
        if(!encoder.matches(oldPassword,u.getPassword()))
            throw new RuntimeException("oldPassword wrong.");
        String result = encoder.encode(newPassword);
        u.setPassword(result);
        RespObj resp = new RespObj(userRepo.save(u));
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        authentication.setAuthenticated(false);
        return resp;
    }
//    @Secured("USER")
//    @PreAuthorize()
//    @Auth
//    @PreAuthorize("")
    @PreAuthorize("authenticated")
    @RequestMapping("curentUser")
    public Object curentUser(@AuthenticationPrincipal org.springframework.security.core.userdetails.User user){
        return new RespObj(user);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值