我使用Spring Security的应用程序不会超出登录页面 [英] My application with Spring Security don't go beyond login page

查看:105
本文介绍了我使用Spring Security的应用程序不会超出登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用Spring Security进行身份验证的项目,该项目使用Java配置而不是XML。这是我的类SecurityConfig.java:

I just started a project with uses Spring Security for authentication which uses Java configuration instead XML. That's my class SecurityConfig.java:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("kleber")
                .password("123")
                .roles("USER");
    }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/spring/index").permitAll()
                            .loginProcessingUrl("/spring/login").permitAll()
                .usernameParameter("login")
                .passwordParameter("senha")
                .defaultSuccessUrl("/spring/home")
                .failureUrl("/spring/erro-login")
                .and()
            .logout()
                .logoutUrl("/spring/logout")
                .logoutSuccessUrl("/spring/index").permitAll();
    }

}

通过这种配置,我可以联系到登录页面,但在我通知我的credencials(用户名和密码)后,系统返回到同一个登录页面,尽管通知的用户名和密码是正确的。

With this configuration, I can reach the login page, but after I inform my credencials (username and password) the system return to this same login page, despite the username and password informed are correct.

所有这一切在SecurityConfig类中通知的URL映射在此控制器中:

All this URLs informed in the class SecurityConfig are mapped in this controller:

@Controller
@RequestMapping(value="spring")
public class SpringController {

    @RequestMapping(value="index")
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("index");
        return mav;
    }

    @RequestMapping(value="home")
    public ModelAndView home() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("home");
        return mav;
    }

    @RequestMapping(value="doLogin", method=RequestMethod.POST)
    public void doLogin(HttpServletRequest request, HttpServletResponse response) {
        //
    }

    @RequestMapping(value="logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath());
    }

}

我做错了什么?

- >仍与上述主题相关:

-->Still related to topic above:

我需要实现这个'loginProcessingUrl',它映射在我的控制器这样:

I need implement this 'loginProcessingUrl', which is mapped in my controller this way:

@RequestMapping(value="doLogin", method=RequestMethod.POST)
public void doLogin(HttpServletRequest request, HttpServletResponse response) {
    //
}

I在我的应用程序中已经有两个类,根据我读过的文章,这个过程是必要的,但我可能错了,也许我需要另一种方法:

I already have in my application two classes which, according to the articles I read, will be necessary for this process, but I could be wrong and maybe i need another approach:

SampleAuthenticationManager

public class SampleAuthenticationManager implements AuthenticationManager {
  static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();

  static
  {
    AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
  }

  public Authentication authenticate(Authentication auth) throws AuthenticationException
  {
    if (auth.getName().equals(auth.getCredentials()))
    {
        return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), AUTHORITIES);
    }
    throw new BadCredentialsException("Bad Credentials");
  }

}

DefaultAuthenticationProcessingFilter

    public class DefaultAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {

    private static final String INTERCEPTOR_PROCESS_URL = "/spring/doLogin";

    private static AuthenticationManager am = new SampleAuthenticationManager();

    protected DefaultAuthenticationProcessingFilter() {
        super(INTERCEPTOR_PROCESS_URL);
        // TODO Auto-generated constructor stub
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        // TODO Auto-generated method stub

        String login = request.getParameter("login");
        String senha = request.getParameter("senha");

        Authentication input = new UsernamePasswordAuthenticationToken(login, senha);
        Authentication output = null;
        try {
            output = am.authenticate(input);
            SecurityContextHolder.getContext().setAuthentication(output);
            getSuccessHandler().onAuthenticationSuccess(request, response, output);
        } catch (AuthenticationException failed) {
            getFailureHandler().onAuthenticationFailure(request, response, failed);
        }

        return output;
    }

}

在这种情况下,我该怎么做从我的控制器实现方法doLogin?请注意,此时我正在使用inMemory身份验证,以便稍后扩展我的项目以使用数据库。

In this scenario, how I should implement the method doLogin from my controller? Take in consideration that in this moment I am using inMemory authentication, for later extend my project for use a database.

推荐答案

好的,我设法解决了我的问题;它发生了我在SecurityConfig中通知的Url和我的观点中的Url's。我需要记住以后:在课堂上,总是使用//。在视图中,请始终使用。

Ok, I managed to solve my problem; it happens I make some mess with the Url informed in the SecurityConfig and the Url's in my views. I need remember in the future: in the class, use always //. In the view, always use .

在我的情况下,视图是这样写的:

In my case, the views was written this way:

index.jsp - >登录页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<c:url value="/spring/login" var="loginUrl"/>
<form method="post" action="${loginUrl}">
    usu&aacute;rio: <input type="text" name="login" size=20> <br/>
    senha: <input type="password" name="senha" size=20> <br/>
    <input type="submit" value="entrar"> <br/>
</form>

</body>
</html>

home.jsp - >命运页面(仪表板):仅用于此项目状态的测试目的

home.jsp -> the "destiny" page (dashboard): only for test purposes in this state of project

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<h2>
    <c:out value="${pageContext.request.remoteUser}"/>
    <a href="<c:out value="${pageContext.request.contextPath}/spring/logout"/>">Logout</a>
</h2>

</body>
</html>

类Sec​​urityConfig.java的最终代码

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("kleber")
                .password("123")
                .roles("USER");
    }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/spring/index").permitAll()
                .loginProcessingUrl("/spring/login").permitAll()
                .usernameParameter("login")
                .passwordParameter("senha")
                .successHandler(new CustomAuthenticationSuccessHandler())
                .failureHandler(new CustomAuthenticationFailureHandler())
                .and()
            .logout()
                .logoutUrl("/spring/logout")
                .logoutSuccessUrl("/spring/index").permitAll();
    }

}

这篇关于我使用Spring Security的应用程序不会超出登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆