spring boot集成Spring Security

Spring Security 介绍

Spring Security 是专门针对基于 Spring 的项目的安全框架,充分利用了依赖注入和 AOP来实现安全的功能。

Spring Boot 集成 Spring Security

Spring boot 支持集成 Spring Security,只需要引入Security依赖

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

Spring boot 为我们默认提供了一系列Spring Security的配置:

security.user.name=user # 默认用户的用户名
security.user.password= # 默认用户的密码
security.user.role=USER # 默认用户的角色
security.ignored= # 无需拦截的路径
...

划重点 security 默认提供的用户的密码在项目启动时生成,打印在控制台。

当然纯粹的使用磨人的配置无法满足我们日常的业务需求,因而我们需要实现一些自定义配置,我们只需要继承 WebSecurityConfigurerAdapter类即可,例如:


@configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	
}

安全认证主要是做了两件事情:认证和授权。认证就是确认用户是可以访问当前系统的,授权就是确定当前用户在系统中所拥有的功能权限。
下面通过一个示例查看SpringSecurity如何完成的这两件事情:


@configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private UserDetailsService userDetailsService;

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

	/**
	 * 用户认证,主要是根据用户名获取用户角色、权限,来匹配用户登录和用户是否有权限操作
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService);
	}

	/**
	 * 访问权限过滤
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// We recommend disabling CSRF protection completely only if you are creating a
		// service that is used by non-browser clients
		// 以此支持非浏览器 post 访问 shutdown 等请求
		http.csrf().disable();
		http.addFilterBefore(new RouterFilter(), AnonymousAuthenticationFilter.class);
		// 默认为 LoginUrlAuthenticationEntryPoint 跳转到登录
		http.exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint());
		http.authorizeRequests()
				.antMatchers(Resources.PUBLIC_URL).permitAll()
				// 安全关闭服务接口,拥有 ADMIN 权限的用户可以访问该 rul
				.antMatchers(HttpMethod.GET, Resources.ADMIN_URL_GET).hasRole("ADMIN")
				.antMatchers(HttpMethod.POST, Resources.ADMIN_URL_POST).hasRole("ADMIN")
				.anyRequest().authenticated() // 任何请求,登录后可以访问
				.and()
					.formLogin()
						.loginPage("/")// 定制登录行为
						.permitAll()
				.and()
					// 开启 basic 认证,若不添加此项,将不能通过 curl 的 basic 方式传递用户信息
					.httpBasic()
				.and()
					// 重定向url由默认值/login?logout改为/
					.logout()
						.logoutSuccessUrl("/")// 定制注销行为
						.permitAll()
						.invalidateHttpSession(true);
	}

	class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
		@Override
		public void commence(HttpServletRequest request, HttpServletResponse response,
				AuthenticationException authException) throws IOException, ServletException {
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			if (RequestUtil.isAjaxOrFetch(request)) {// ajax 和 fetch 都返回指定的 ResultInfo
				response.setContentType("application/json; charset=utf-8");
				ResultInfo<String> result = new ResultInfo<String>();
				result.setMsg(authException.getMessage());
				result.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
				result.setSuccess(false);
				response.sendError(HttpServletResponse.SC_UNAUTHORIZED, JSONUtil.stringify(result));
			} else {
				response.setContentType("text/html; charset=utf-8");
				request.getRequestDispatcher("error/404").forward(request, response);
			}
		}
	}
}
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserInfo userInfo = userService.getByLoginName(username);
		if (userInfo == null) {
			throw new UsernameNotFoundException(username + " 不存在!");
		}
		// 加密密码
		String encode = passwordEncoder.encode(UserSecurity.getInternalPassword());
		if (userInfo.isAdmin()) {
			return new User(username, encode, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"));
		} else {
			return new User(username, encode, AuthorityUtils.commaSeparatedStringToAuthorityList(""));
		}
	}

}

上述代码中通过configure(AuthenticationManagerBuilder auth) 方法来进行用户认证,通过configure(HttpSecurity http)方法实现授权控制。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值