问题:不添加权限控制,页面可以正常访问,添加后页面无法正常访问(未进入控制层),权限认证正常 代码如下: 1. WebSecurityConfig.java package com.player.config; import com.player.handler.AuthenticationProviderCustom ..

求助!!!SpringSecurity 配置单点登录问题

本贴最后更新于 893 天前,其中的信息可能已经时异事殊

问题:不添加权限控制,页面可以正常访问,添加后页面无法正常访问(未进入控制层),权限认证正常

代码如下:

1. WebSecurityConfig.java

package com.player.config;

import com.player.handler.AuthenticationProviderCustom;
import com.player.handler.UserDetailsServiceCustom;
import com.player.repository.AuthorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * Created by ronger on 2017/6/24. */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
  private AuthorRepository authorRepository;

  @Bean
  public UserDetailsService userDetailsService(){
        UserDetailsService userDetailsService=new UserDetailsServiceCustom(authorRepository);
 return userDetailsService;
  }

    @Bean
  public AuthenticationProvider authenticationProvider(){
        AuthenticationProvider authenticationProvider = new AuthenticationProviderCustom(userDetailsService());
 return authenticationProvider;
  }

    /**
 * 匹配 "/" 路径,不需要权限即可访问
  * 匹配 "/user" 及其以下所有路径,都需要 "USER" 权限
  * 登录地址为 "/login",登录成功默认跳转到页面 "/user"
 * 退出登录的地址为 "/logout",退出成功后跳转到页面 "/login"
 * 默认启用 CSRF
 */  @Override
  protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/upload/**").hasRole("USER")
                .antMatchers("/admin/**").hasRole("ADMIN")
                .and()
                .formLogin().loginPage("/login").defaultSuccessUrl("/index").failureUrl("/login?error").usernameParameter("username").passwordParameter("password").permitAll()
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login");
  }

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

    /**
 * 添加 UserDetailsService, 实现自定义登录校验
  */
  @Override
  protected void configure(AuthenticationManagerBuilder builder) throws Exception{
        //暂时使用基于内存的AuthenticationProvider
 //builder.inMemoryAuthentication().withUser("username").password("password").roles("USER"); //自定义AuthenticationProvider
  builder.authenticationProvider(authenticationProvider());
  }

}

2. UserDetailsServiceCustom.java


package com.player.handler;

import com.player.repository.AuthorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * Created by ronger on 2017/6/24. */
 public class UserDetailsServiceCustom implements UserDetailsService {

    @Autowired
  private AuthorRepository authorRepository;

 public UserDetailsServiceCustom(AuthorRepository authorRepository) {
        this.authorRepository = authorRepository;
  }

    @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return authorRepository.findByUsernameWithAuthorities(username);
  }
}

3. AuthenticationProviderCustom.java


package com.player.handler;

import com.player.util.MD5Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * Created by ronger on 2017/6/24. */
 public class AuthenticationProviderCustom implements AuthenticationProvider {

    @Autowired
  private UserDetailsService userDetailsService;

 public AuthenticationProviderCustom(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
  }

    @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        try{
            UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
  String account = token.getName();
  //从数据库找到的用户
  UserDetails userDetails = null;
 if(account != null) {
                userDetails = userDetailsService.loadUserByUsername(account);
  }
            //
  if(userDetails == null) {
                throw new UsernameNotFoundException("用户名/密码无效");
  }else if (!userDetails.isEnabled()){
                throw new DisabledException("用户已被禁用");
  }else if (!userDetails.isAccountNonExpired()) {
                throw new AccountExpiredException("账号已过期");
  }else if (!userDetails.isAccountNonLocked()) {
                throw new LockedException("账号已被锁定");
  }else if (!userDetails.isCredentialsNonExpired()) {
                throw new LockedException("凭证已过期");
  }
            //数据库用户的密码
  String password = userDetails.getPassword();
  //与authentication里面的credentials相比较
  if(!password.equals(MD5Tools.MD5(token.getCredentials().toString()))) {
                throw new BadCredentialsException("Invalid username/password");
  }
            //授权
  return new UsernamePasswordAuthenticationToken(userDetails, password,userDetails.getAuthorities());
  }catch (Exception e){
            e.printStackTrace();
  }
        return null;
  }

    @Override
  public boolean supports(Class authentication) {
        //返回true后才会执行上面的authenticate方法,这步能确保authentication能正确转换类型
  return UsernamePasswordAuthenticationToken.class.equals(authentication);
  }

}
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    2465 引用 • 7872 回帖 • 863 关注
  • IDEA

    IDEA 全称 IntelliJ IDEA,是一款 Java 语言开发的集成环境,在业界被公认为最好的 Java 开发工具之一。IDEA 是 JetBrains 公司的产品,这家公司总部位于捷克共和国的首都布拉格,开发人员以严谨著称的东欧程序员为主。

    121 引用 • 353 回帖 • 601 关注
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    659 引用 • 1233 回帖 • 759 关注
10 回帖
请输入回帖内容...
  • Vanessa

    这个代码贴的没有被正确解析呀 @88250

    1 回复
  • 88250

    他没有用 markdown

  • ronger

    终于捋顺了 😑

    1 回复
  • Vanessa

    没顺呀。还是乱的

    1 回复
  • ronger

    哈哈,我说的是我的代码实现,不是贴子内的,等我学会了 Markdown 再来捋顺贴子哈 😄

    1 回复
  • Vanessa

    markdown 很简单的。可以参看 https://hacpai.com/guide/markdown

    1 回复
  • ronger

    改好了 😃

    1 回复
  • Vanessa

    So Cool

  • liiihhhh

    你这个配置应该不是单点登录吧。

    先在 application.properties中加一句 logging.level.org.springframework.security=DEBUG

    在访问页面,看看日志才能确定问题

    1 回复
  • ronger

    哈哈,刚入 SpringSecurity 坑,目前可以正常的登录了。谢谢

请输入回帖内容 ...