栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

牛客网项目——前置技术(十):Spring Security

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

牛客网项目——前置技术(十):Spring Security

文章目录
  • 1. JavaEE和SpringMVC
  • 2. 简化版社区
  • 2. 配置Spring Security
    • 2.1 pom.xml引入依赖
    • 2.2 user实体类
    • 2.3 UserService
    • 2.4 SecurityConfig 配置类
    • 2.5 HomeController

1. JavaEE和SpringMVC

Spring Security就是通过11个Fliter进行组合管理

2. 简化版社区

只保留登录相关代码

2. 配置Spring Security 2.1 pom.xml引入依赖

	org.springframework.boot
	spring-boot-starter-security

导入之后默认生成一个账号密码还有登录页,管理立即生效

2.2 user实体类

user.type字段,0普通用户,1超级管理员,2版主
补全get set tostring

  1. 实现接口UserDetails,重写以下方法
// true: 账号未过期.
@Override
public boolean isAccountNonExpired() {
    return true;
}

// true: 账号未锁定.
@Override
public boolean isAccountNonLocked() {
    return true;
}

// true: 凭证未过期.
@Override
public boolean isCredentialsNonExpired() {
    return true;
}

// true: 账号可用.
@Override
public boolean isEnabled() {
    return true;
}

//获取当前用户权限列表
@Override
public Collection getAuthorities() {
    List list = new ArrayList<>();
    list.add(new GrantedAuthority() {
        @Override
        public String getAuthority() {
            switch (type) {
                case 1:
                    return "ADMIN";
                default:
                    return "USER";
            }
        }
    });
    return list;
}
2.3 UserService

实现接口UserDetailsService

  1. 重写方法loadUserByUsername
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    return this.findUserByName(username);
}
2.4 SecurityConfig 配置类
  1. 继承父类WebSecurityConfigurerAdapter
  2. 注入UserService
  3. 重写configure(WebSecurity web),忽略静态资源的访问
@Override
public void configure(WebSecurity web) throws Exception {
    // 忽略静态资源的访问
    web.ignoring().antMatchers("/resources/**");
}
  1. 重写configure(AuthenticationManagerBuilder auth),这个方法主要是做认证。
    1. AuthenticationManager: 认证的核心接口
    2. AuthenticationManagerBuilder: 用于构建AuthenticationManager对象的工具
    3. ProviderManager: AuthenticationManager接口的默认实现类
// AuthenticationManager: 认证的核心接口.
// AuthenticationManagerBuilder: 用于构建AuthenticationManager对象的工具.
// ProviderManager: AuthenticationManager接口的默认实现类.
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // 内置的认证规则
    // auth.userDetailsService(userService).passwordEncoder(new Pbkdf2PasswordEncoder("12345"));

    // 自定义认证规则
    // AuthenticationProvider: ProviderManager持有一组AuthenticationProvider,每个AuthenticationProvider负责一种认证.
    // 委托模式: ProviderManager将认证委托给AuthenticationProvider.
    auth.authenticationProvider(new AuthenticationProvider() {
        // Authentication: 用于封装认证信息的接口,不同的实现类代表不同类型的认证信息.
        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            String username = authentication.getName();
            String password = (String) authentication.getCredentials();

            User user = userService.findUserByName(username);
            if (user == null) {
                throw new UsernameNotFoundException("账号不存在!");
            }

            password = CommunityUtil.md5(password + user.getSalt());
            if (!user.getPassword().equals(password)) {
                throw new BadCredentialsException("密码不正确!");
            }

            // principal: 主要信息; credentials: 证书; authorities: 权限;
            return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
        }

        // 当前的AuthenticationProvider支持哪种类型的认证.
        @Override
        public boolean supports(Class aClass) {
            // UsernamePasswordAuthenticationToken: Authentication接口的常用的实现类.
            return UsernamePasswordAuthenticationToken.class.equals(aClass);
        }
    });
}
  1. 重写configure(HttpSecurity http)
    1. 配置登陆页面http.formLogin()
    2. 登录成功处理器.successHandler
    3. 登录失败处理器.failureHandler
    4. 退出相关配置http.logout()
    5. 授权配置http.authorizeRequests()
    6. 验证码在验证账号之前
 @Override
protected void configure(HttpSecurity http) throws Exception {
    // 登录相关配置
    http.formLogin()
            .loginPage("/loginpage")
            .loginProcessingUrl("/login")
            .successHandler(new AuthenticationSuccessHandler() {
                @Override
                public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                    response.sendRedirect(request.getContextPath() + "/index");
                }
            })
            .failureHandler(new AuthenticationFailureHandler() {
                @Override
                public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                    request.setAttribute("error", e.getMessage());
                    request.getRequestDispatcher("/loginpage").forward(request, response);
                }
            });

    // 退出相关配置
    http.logout()
            .logoutUrl("/logout")
            .logoutSuccessHandler(new LogoutSuccessHandler() {
                @Override
                public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                    response.sendRedirect(request.getContextPath() + "/index");
                }
            });

    // 授权配置
    http.authorizeRequests()
            .antMatchers("/letter").hasAnyAuthority("USER", "ADMIN")
            .antMatchers("/admin").hasAnyAuthority("ADMIN")
            .and().exceptionHandling().accessDeniedPage("/denied");

    // 增加Filter,处理验证码
    http.addFilterBefore(new Filter() {
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            if (request.getServletPath().equals("/login")) {
                String verifyCode = request.getParameter("verifyCode");
                if (verifyCode == null || !verifyCode.equalsIgnoreCase("1234")) {
                    request.setAttribute("error", "验证码错误!");
                    request.getRequestDispatcher("/loginpage").forward(request, response);//转发
                    return;
                }
            }
            // 让请求继续向下执行.
            filterChain.doFilter(request, response);
        }
    }, UsernamePasswordAuthenticationFilter.class);

    // 记住我
    http.rememberMe()
            .tokenRepository(new InMemoryTokenRepositoryImpl())
            .tokenValiditySeconds(3600 * 24)
            .userDetailsService(userService);

}
2.5 HomeController

在首页添加欢迎信息,通过SecurityContextHolder获取登陆者信息

@RequestMapping(path = "/index", method = RequestMethod.GET)
public String getIndexPage(Model model) {
    // 认证成功后,结果会通过SecurityContextHolder存入SecurityContext中.
    Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (obj instanceof User) {
        model.addAttribute("loginUser", obj);
    }
    return "/index";
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/943393.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号