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

springboot+springsecurity+jwt前后端分离

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

springboot+springsecurity+jwt前后端分离

目录

maven 依赖

selfUserDetails

SelfUserDetailsService

DefaultPasswordEncoder

JwtTokenUtil

MyAccessDenieDHandler

TokenAuthenticationFilter

TokenLoginFilter

UnauthorizedEntryPorint


maven 依赖
 
            org.springframework.boot
            spring-boot-starter-security
        
        
            org.springframework.security
            spring-security-test
        

            io.jsonwebtoken
            jjwt
            0.9.0
        

文件目录

 

SpringSecurityConfig

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    DefaultPasswordEncoder defaultPasswordEncoder;
    @Autowired
   SelfUserDetailsService selfUserDetailsService;
   @Autowired
   AppFilterInvocationSecuritymetadataSource appFilterInvocationSecuritymetadataSource;
   @Autowired
   CustomerAccessDecisionManger customerAccessDecisionManger;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 加入自定义的安全认证
//        auth.authenticationProvider(provider);

        auth.userDetailsService(selfUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .exceptionHandling()

                //未授权处理
                .authenticationEntryPoint(new UnauthorizedEntryPoint())
                .accessDeniedHandler(new MyAccessDeniedHandler())
                .and().authorizeRequests().withObjectPostProcessor(new ObjectPostProcessor() {
            @Override
            public  O postProcess(O o) {
                o.setSecuritymetadataSource(appFilterInvocationSecuritymetadataSource);
                o.setAccessDecisionManager(customerAccessDecisionManger);
                return o;
            }
        })
                .anyRequest().authenticated()
                .and().csrf().disable()
                .logout().logoutUrl("/logout")
                .and()
                //.addLogoutHandler(new TokenLogoutHandler(tokenManager))
                .addFilter(new TokenAuthenticationFilter(authenticationManager()))
                .addFilter(new TokenLoginFilter(authenticationManager())).httpBasic();
    }

    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
@Bean
    public DefaultPasswordEncoder CreateEncoder(){
        return new DefaultPasswordEncoder();
}

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/Account
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication auth) throws IOException, ServletException {

        SelfUserDetails user= (SelfUserDetails) auth.getPrincipal();
        Account account = user.getAccount();
        String authrorities = user.getAuthorities().size() > 0 ? user.getAuthorities().toString().replaceAll("(?:\[|null|\]| +)", "") : user.getAuthorities().toString();
        String token=JwtTokenUtil.createToken(account.getName(),authrorities);
        HashMap map = new HashMap<>();
        map.put("token", token);
        map.put("user",account);

        ResponseUtil.out(response, Result.successWithData(map));
    }
    
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        logger.debug("登录失败!");
        ResponseUtil.out(response, Result.failed("登录失败"));
    }
}

UnauthorizedEntryPorint
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
         ResponseUtil.out(httpServletResponse, Result.failed("未授权统一处理"));
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/397012.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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