SpringBoot Security完成认证和授权
认证:
package com.vn.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyWebConfig implements WebMvcConfigurer { //默认Url根路径跳转到/login,此url为spring security提供 @Override public void addViewControllers(ViewControllerRegistry registry) { // spring security提供默认路径 registry.addViewController("/").setViewName("redirect:/login"); // 自定义跳转路径 /*registry.addViewController("/").setViewName("redirect:/index.html");*/ } /** * 自行注入一个PasswordEncoder。 * Security会优先从Spring容器中获取PasswordEncoder. * 注入一个不做任何加解密操作的密码处理器用作演示。 * 一般常用BCryptPasswordEncoder * * @return */ @Bean public PasswordEncoder getPassWordEncoder() { return new BCryptPasswordEncoder(10); // return NoOpPasswordEncoder.getInstance(); } /** * 自行注入一个UserDetailsService * 如果没有的话,在UserDetailsServiceAutoConfiguration中会默认注入一个包含user * 用户的InMemoryUserDetailsManager * * @return */ @Bean public UserDetailsService userDetailsService() { InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(User.withUsername("admin") .password("admin").authorities("mobile", "salary").build() , User.withUsername("manager").password("manager").authorities("salary").build() , User.withUsername("worker").password("worker").roles("worker").build()); return userDetailsManager; } }
注入校验配置规则(授权):
package com.vn.config; import org.springframework.context.annotation.Configuration; 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.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * 校验规则配置 */ @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter { //配置安全拦截策略 @Override protected void configure(HttpSecurity http) throws Exception { //链式配置拦截策略 http.csrf().disable()//关闭csrg跨域检查 //这里注意matchere是有顺序的。 .authorizeRequests() .antMatchers("/mobile/**").hasAuthority("mobile") .antMatchers("/salary/**").hasAuthority("salary") //等价于hasRole("worker") .antMatchers("/worker/**").hasAuthority("ROLE_worker") //common下的请求直接通过 .antMatchers("/common/**").permitAll() //放行静态资源 .antMatchers("/**.html", "/js/**", "/css/**", "/img/**").permitAll() //其他请求需要登录 .anyRequest().authenticated() //并行条件 .and() .formLogin() // .successHandler((request,response,authentication)->{ // response.setContentType("application/json;charset=utf-8"); // PrintWriter out = response.getWriter(); // out.write(authentication.getName()); // out.flush(); // out.close(); // }) //自定义登录页面 .loginPage("/index.html") //可从默认的login页面登录,并且登录后跳转到main.html .defaultSuccessUrl("/main.html").failureUrl("/common/loginFailed"); } //创建默认用户的第二个方案 // @Override // protected void configure(AuthenticationManagerBuilder auth) throws Exception { //// auth.userDetailsService(userDetailsService()); // auth.inMemoryAuthentication() // .withUser(User.withUsername("admin").password("admin").authorities("mobile","salary").build()) // .withUser(User.withUsername("manager").password("manager").authorities("salary").build()) // .withUser(User.withUsername("worker").password("worker").authorities("worker").build()); // } // // @Bean // @Override // public AuthenticationManager authenticationManagerBean() throws Exception { // return super.authenticationManagerBean(); // } }
获取当前用户信息:Spring Security提供了多种获取当前用户信息的方法
package com.vn.controller; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.security.Principal; /** * @author VN */ @RestController @RequestMapping("/common") public class LoginController { @GetMapping("/getLoginUserByPrincipal") public String getLoginUserByPrincipal(Principal principal) { return principal.getName(); } @GetMapping(value = "/getLoginUserByAuthentication") public String currentUserName(Authentication authentication) { return authentication.getName(); } @GetMapping(value = "/username") public String currentUserNameSimple(HttpServletRequest request) { Principal principal = request.getUserPrincipal(); return principal.getName(); } @GetMapping("/getLoginUser") public String getLoginUser() { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return user.getUsername(); } }

浙公网安备 33010602011771号