虽然登录成功,但使用spring security后无法访问主页

pw9qyyiw  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(557)

我想将安全部分添加到项目中,我正在使用springsecurity来提供后端安全性。当我添加自定义登录过滤器时 AbstractAuthenticationProcessingFilter 关于spring security,我遇到了一个关于跨源问题的错误。现在我又加了一句 http.cors(); 到websecurityconfig,我再也不会收到跨源错误了。
我正在向后端发送请求 http://localhost:8081/user/sys-role/verifyTargetUrl . 现在,确切的错误是 Uncaught (in promise) Error: Infinite redirect in navigation guard at eval (vue-router.esm-bundler.js?6c02:2913) . 因此,不知何故,前端vue路由器守卫发现自己在一个无限的循环。我将感谢你的任何帮助。

更新:

结果我没有得到200的响应码,这导致了vue路由器中的无限循环。我的问题变成了纯spring安全问题,因为vue路由器似乎没有问题。我发了一封邮件到 http://localhost:8081/user/sys-role/verifyTargetUrl 但是我的请求没有进入后台的postmapping。而是输入下面显示的customauthenticationentrypoint并将代码设置为504。但在verifytargeturl的后端我设置为200。除此之外, onAuthenticationSuccessCustomAuthenticationSuccessfulHandler 也在后端调用。

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

    Message msg=new Message();
    msg.setCode(504);
    msg.setMsg("authenticate fail");

    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
    httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.toString());
    httpServletResponse.getWriter().write(JSON.toJSONString(msg));
}

}

浏览器控制台: config: {url: "http://localhost:8081/user/sys-role/verifyTargetUrl", method: "post", data: "{"userId":1017,"targetUrl":"/Main"}", headers: {…}, transformRequest: Array(1), …} data: {code: 504, msg: "authenticate fail"}更新2:更多代码

customjsonloginfilter.java文件

public class CustomJSONLoginFilter  extends AbstractAuthenticationProcessingFilter {

private final ISysUserService iUserService;

public CustomJSONLoginFilter(String defaultFilterProcessesUrl, ISysUserService iUserService) {
    super(new AntPathRequestMatcher(defaultFilterProcessesUrl, HttpMethod.POST.name()));
    this.iUserService = iUserService;
}

@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
    JSONObject requestBody=  getRequestBody(httpServletRequest);
    String username= requestBody.getString("username");
    String password= requestBody.getString("password");

    // get user info  by username
    SysUser sysUser= iUserService.getUserInfoByUsername(username);

    //verify password
    String encorderType=EncryptionAlgorithm.ENCODER_TYPE.get(1);
    PasswordEncoder passwordEncoder =EncryptionAlgorithm.ENCODER_MAP.get(encorderType);
    System.out.println(passwordEncoder);
    System.out.println(sysUser);
    System.out.println(password);
    if(sysUser==null){
        throw new UsernameNotFoundException("can't find userinfo by username:"+username);
    }else if(!passwordEncoder.matches(password,sysUser.getPassword())){
        throw new BadCredentialsException("password wrong!");
    }else{
        List<SysRole> list= iUserService.findRolesByUsername(username);
        List<SimpleGrantedAuthority> simpleGrantedAuthorities=  new ArrayList<SimpleGrantedAuthority>();

        Iterator<SysRole> i=list.iterator();
        while(i.hasNext()){
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(i.next().getRoleName()));
        }

        return new UsernamePasswordAuthenticationToken(username,password,simpleGrantedAuthorities);
    }

}

private JSONObject getRequestBody(HttpServletRequest request) throws AuthenticationException{
    try {
        StringBuilder stringBuilder = new StringBuilder();
        InputStream inputStream = request.getInputStream();
        byte[] bs = new byte[StreamUtils.BUFFER_SIZE];
        int len;
        while ((len = inputStream.read(bs)) != -1) {
            stringBuilder.append(new String(bs, 0, len));
        }
        return JSON.parseObject(stringBuilder.toString());
    } catch (IOException e) {
        System.out.println("get request body error.");
    }
    throw new AuthenticationServiceException("invalid request body");
}
tzcvj98z

tzcvj98z1#

我不会写一个自定义的安全性,但使用Spring Security ,他们有一个强大的库,并已为您解决了,这是一个配置问题!
我的计划很容易实现!我有一个存储
Kotlin代码

var username: String? = null
    var password: String? = null
    var active: Boolean = false
    var confirmationToken: String? = null // email confirmationToken sent @ registration and other admin functions
    var token: String? = null // If JWT token exist (not NULL or "") then the Networker is logged in with Client!
    var roles: String? = null
    var permissions: String? = null

ADD CONSTRUCTORS ....

    val roleList: List<String>
        get() = if (this.roles?.isNotEmpty()!!) {
            listOf(*this.roles?.split(",".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()!!)
        } else ArrayList()

    val permissionList: List<String>
        get() = if (this.permissions?.isNotEmpty()!!) {
            listOf(*this.permissions?.split(",".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()!!)
        } else ArrayList()

从那里我配置了安全配置

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.authentication.dao.DaoAuthenticationProvider
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.util.matcher.AntPathRequestMatcher

@Configuration
@EnableWebSecurity
class SecurityConfiguration(private val userPrincipalDetailService: UserPrincipalDetailService) :
    WebSecurityConfigurerAdapter() {

    override fun configure(auth: AuthenticationManagerBuilder) {
        auth.authenticationProvider(authenticationProvider())
    }

    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        http.authorizeRequests()
            .antMatchers("/index.html").permitAll()
            .antMatchers("/security/**").permitAll()
            .antMatchers("/profile/**").authenticated()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .and().formLogin()
            .defaultSuccessUrl("/profile/index", true)
            .loginProcessingUrl("/security/login")
            .loginPage("/security/login").permitAll()
            .usernameParameter("username")
            .passwordParameter("password")
            .and().logout()
            .invalidateHttpSession(true)
            .clearAuthentication(true)
            .deleteCookies("JSESSIONID")
            .logoutRequestMatcher(AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/security/login")
            .and()
            .rememberMe().tokenValiditySeconds(2592000) // 2592000 = 30 days in Seconds
            .rememberMeParameter("rememberMe")
    }

    private fun authenticationProvider(): DaoAuthenticationProvider {
        val daoAuthenticationProvider = DaoAuthenticationProvider()
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder())
        daoAuthenticationProvider.setUserDetailsService(this.userPrincipalDetailService)

        return daoAuthenticationProvider
    }

    @Bean
    internal fun passwordEncoder(): PasswordEncoder {
        return BCryptPasswordEncoder()
    }
}

如果你想学习SpringSecurity的课程,你可以学习罗马尼亚程序员的这个SpringBootSecurity

相关问题