spring security基本原理

image.png

首先先进行配置类的配置 继承WebSecurityConfigurerAdapter适配器

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

        /**
         * 注册加密方式
         * 自定义加密的话实现PasswordEncoder接口即可
         * @return
         */
        @Bean
        public PasswordEncoder passwordEncoder() {
                return new BCryptPasswordEncoder();
        }

        /**
         * 注册授权认证通道
         * @param http
         * @throws Exception
         */
        @Override
        protected void configure(HttpSecurity http) throws Exception {
                super.configure(http);
                /**
                 * 表单授权身份认证 认证请求 任何请求 授权 (全栈开发)
                 */
//              http.formLogin()//表单登陆
//////              http.httpBasic() //正常登陆
////                                //跳转登陆页面
////                                .loginPage("/imooc-signIn.html")
////                                //让security通过其他url来post请求(默认是"/login")
////                                .loginProcessingUrl("authentication/form")
////                                .and()
////                                .authorizeRequests()
////                                //跳转到此页面时不需要身份认证 防止登陆页被认证过滤
////                                .antMatchers("/imooc-signIn.html").permitAll()
////                                .anyRequest()
////                                .authenticated()
////                                .and()
////                                //关闭跨站请求伪造
////                                .csrf().disable();
                /**
                 * 表单授权身份认证 认证请求 任何请求 授权 (前后端分离 resful风格)
                 */
                http.formLogin()//表单登陆
//              http.httpBasic() //正常登陆
                                //跳转登陆页面
                                .loginPage("/authentication/require")
                                //让security通过其他url来post请求(默认是"/login")
                                .loginProcessingUrl("authentication/form")
                                .and()
                                .authorizeRequests()
                                //跳转到此页面时不需要身份认证 防止登陆页被认证过滤
                                .antMatchers("/authentication/require").permitAll()
                                .anyRequest()
                                .authenticated()
                                .and()
                                //关闭跨站请求伪造
                                .csrf().disable();
        }
}

登陆服务如何调用 新建用户服务类

@Component
public class MyUserDetailsService implements UserDetailsService {

        private Logger logger = LoggerFactory.getLogger(getClass());

        @Autowired
        private PasswordEncoder passwordEncoder;

        /**
         * 根据用户名查询数据库返回用户对象
         *
         * @param username
         * @return
         * @throws UsernameNotFoundException
         */
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                //这里加入数据库逻辑
                logger.info("表单登录用户名:" + username);
                return buildUser(username);
        }

        /**
         * 实际开发中的注意事项
         * enabled :用于用户是否被删除
         * accountNonExpired: 账户是否失效
         * credentialsNonExpired: 密码是否失效
         * accountNonLocked: 账户是否被锁定
         * enabled
         *
         * @param username
         * @return
         */
        private User buildUser(String username) {
                // 根据用户名查找用户信息
                //根据查找到的用户信息判断用户是否被冻结
                String password = passwordEncoder.encode("123456");
                logger.info("数据库密码是:" + password);
                return new User(username, password,
                                true, true, true, true,
                                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        }

}

前端控制器

@RestController
public class BrowserSecurityController {

        private Logger logger = LoggerFactory.getLogger(getClass());

        //请求缓存
        private RequestCache requestCache = new HttpSessionRequestCache();

        //
        private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();


        /**
         * 当需要身份认证时 跳转到这里
         * @param request
         * @param response
         * @return
         */
        @RequestMapping("/authentication/require")
        @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
        public SimpleResponse requireAuthtication(HttpServletRequest request, HttpServletResponse response) throws IOException {
                SavedRequest savedRequest = requestCache.getRequest(request, response);

                if (savedRequest != null) {
                        String redirectUrl = savedRequest.getRedirectUrl();
                        logger.info("引发跳转的请求是: {}" ,redirectUrl);
                        //如果引发跳转的请求是html结尾的 就直接跳转到登陆页上
                        if (StringUtils.endsWithIgnoreCase(redirectUrl, ".html")) {
                                redirectStrategy.sendRedirect(request, response, "登陆页面.html");
                        }
                }

                return new SimpleResponse("访问的服务需要身份认证, 请引导用户到登陆页面");

        }

}

你可能感兴趣的:(spring security基本原理)