springboot集成security安全框架

本文详细介绍SpringBoot中集成Spring Security框架的过程,包括安全框架的简介、依赖导入、YAML配置、核心代码实现及用户信息获取。通过实例展示如何进行用户认证与授权,实现页面的权限控制。

springboot集成security安全框架简单使用

security简介

一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方式的安全框架(简单说是对访问权限进行控制嘛),应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。 spring security的主要核心功能为 认证和授权,所有的架构也是基于这两个核心功能去实现的。

导入依赖

		//安全框架
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>2.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.7.RELEASE</version>
        </dependency>

关于yml配置文件

如果只用security安全框架,可以没有yml配置文件,只要配置服务端口就行了

核心代码

package org.gzy.security;

import org.springframework.beans.factory.annotation.Autowired;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


	/**
	*创建一个类,继承WebSecurityConfigurerAdapter
	*重写下面的方法
	*/
@EnableWebSecurity
@Configuration
public class MySecurity extends WebSecurityConfigurerAdapter{
	@Autowired
	UserDetailsImpl userDetailsImpl;
	@Autowired
	private BCryptPasswordEncoder bCryptPasswordEncoder;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//把安全框架的页面替换为自己的页面
		http.formLogin().loginPage("/html/login.html")
		//提交的后台方法
		.loginProcessingUrl("/loginUser")
		//设置验证的账号密码字段
		.usernameParameter("user_username").passwordParameter("user_password")
		//验证成功
		.successForwardUrl("/loginUser")
		//失败去的方法
		.failureForwardUrl("/errLogin")
		.permitAll();
		//放行的地址 默认从static下
		http.authorizeRequests().antMatchers("/*","/myresource/**","/echarts.js","/angular.js","/html/register.html","/loginUser").permitAll();
		//拦截所有
		http.authorizeRequests().antMatchers("/html/itemList.html").fullyAuthenticated();
		http.csrf().disable();

	}
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsImpl).passwordEncoder(new PasswordEncoder() {
			//密码加密
			@Override
			public String encode(CharSequence rawPassword) {
				// TODO Auto-generated method stub
				return rawPassword.toString();
			}
			//密码解密
			@Override
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
				// TODO Auto-generated method stub
				boolean matches = bCryptPasswordEncoder.matches(rawPassword, encodedPassword);
				return matches;
			}
		});
	}
	
}

获取登录用户的信息

package org.gzy.security;

import com.alibaba.dubbo.config.annotation.Reference;
import org.gzy.entity.User;
import org.gzy.service.UserInterface;
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.Component;

@Component
public class UserDetailsImpl implements UserDetailsService{

	@Reference
    UserInterface userInterface;
	
	@Override
	public UserDetails loadUserByUsername(String user_username) throws UsernameNotFoundException {

		User user = userInterface.selectOne(user_username);
		//System.out.println("===="+user);
		if(user!=null) {
			return (UserDetails) user;
		}
		return null;
	}

}

实体类

package org.gzy.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;

/**
 *实体类实现UserDetails,重写它的所有方法
 * Created by ReadyPlayerOne on 2019/12/6.
 */
@Entity
@Table(name = "user")
public class User implements UserDetails{
    @Id
    private String user_uid;
    private String user_username;
    private String user_password;
    private String user_sex;
    private Integer user_age;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date user_birthday;
    private String user_phone;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

	//改成自己的密码字段
    @Override
    public String getPassword() {
        return user_password;
    }

	//改成自己的用户名字段
    @Override
    public String getUsername() {
        return user_username;
    }

	//下面四个方法默认为false,设置为true表示信任该用户
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

配置完成后,启动项目访问页面,就可以愉快的拦截你想拦截的页面了

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值