Spring Boot图书管理系统项目实战-3.用户登录

导航:

pre:  2.项目搭建

next:4.基础信息管理

 

只挑重点的讲,具体的请看项目源码。

1.项目源码

需要的朋友请给个赞,并留下邮箱,给你们发!

 

2.登录页设计

Spring Boot图书管理系统项目实战-3.用户登录_第1张图片




    
    登录
    
    
    
    
    
    
    








 

3.spring security配置类

/**
 * Spring Security配置
 *
 * @author laoxu
 * @create 2018-10-26
 **/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/*    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource);
    }*/
    @Autowired
    MyAuthenctiationSuccessHandler myAuthenctiationSuccessHandler;

    @Resource
    private DataSource dataSource;

    @Resource(name = "userDetailServiceImpl")
    private UserDetailServiceImpl userService;

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        // 配置数据源
        jdbcTokenRepository.setDataSource(dataSource);
        // 第一次启动的时候自动建表(可以不用这句话,自己手动建表,源码中有语句的)
//        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new MyPasswordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/book/list").permitAll()
                .antMatchers("/bookDetail/*").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/login").permitAll().successHandler(myAuthenctiationSuccessHandler)
                .and().logout().permitAll()
                .and().headers().frameOptions().disable()
        ;

        //开启记住我功能
        //http.rememberMe().tokenRepository(persistentTokenRepository()).userDetailsService(userService).tokenValiditySeconds(86400);
        //http.rememberMe().rememberMeParameter("remember-me").key("laoxu").tokenValiditySeconds(86400);
        http.csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //忽略
        web.ignoring().antMatchers("/static/**");
        web.ignoring().antMatchers("/","/index");
    }
}

 

4.登录成功处理器

/**
 * @Description: 自定义登录成功处理类
 * @Author laoxu
 * @Date 2019/5/25 23:32
 **/
@Component
public class MyAuthenctiationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");

        RequestCache cache = new HttpSessionRequestCache();
        SavedRequest savedRequest = cache.getRequest(request, response);
        // 如果来源请求为空则跳转到管理后台
        String url = "admin";
        /*if((savedRequest==null)){
            url = "admin";
        }else{
            url = savedRequest.getRedirectUrl();
        }*/

        // 获取登录用户详细信息
        User user = userService.getUserByUsername(SecurityUtil.getLoginUser());
        request.getSession().setAttribute("loginUser",user);

        // 返回jwt

        response.sendRedirect(url);
    }
}

 

5.自定义UserService实现

 

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            User user = userService.getUserByUsername(username);
            if (user == null) {
                throw new UsernameNotFoundException("用户:"+username+"不存在!");
            }
            //用户权限
            List authorities = new ArrayList<>();
            /*if (StringUtils.isNotBlank(user.getRoles())) {
                String[] roles = user.getRoles().split(",");
                for (String role : roles) {
                    if (StringUtils.isNotBlank(role)) {
                        authorities.add(new SimpleGrantedAuthority(role.trim()));
                    }
                }
            }*/
            return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

 

 

 

需要源码的朋友留下邮箱:)

 

 

 

 

你可能感兴趣的:(#,Spring-Boot,Java项目实战)