2016-10-16 3 views
1

스프링 보안, 스프링 MVC 및 JPA를 사용하여 HTML에서 로그인 할 때 오류가 있습니다.스프링 보안/MVC/JPA -> 요청 방법 'POST'가 지원되지 않습니다.

@Configuration 
@EnableWebSecurity 
@ComponentScan(basePackageClasses = CustomUserDetailsService.class) 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
private UserDetailsService userDetailsService; 

@Autowired 
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { 
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder()); 
} 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.authorizeRequests() 
      .antMatchers("/hello").access("hasRole('ROLE_ADMIN')") 
      .anyRequest().permitAll() 
      .and() 
      .formLogin().loginPage("/login") 
      .usernameParameter("username").passwordParameter("password") 
      .and() 
      .logout().logoutSuccessUrl("/login?logout") 
      .and() 
      .exceptionHandling().accessDeniedPage("/403") 
      .and() 
      .csrf(); 
} 

@Bean(name = "passwordEncoder") 
public PasswordEncoder passwordencoder() { 
    return new BCryptPasswordEncoder(); 
} 
} 

된 UserDetails 서비스 클래스 :

@Service("customUserDetailsService") 
public class CustomUserDetailsService implements UserDetailsService { 
private final UserRepository userRepository; 
private final UserRolesRepository userRolesRepository; 

@Autowired 
public CustomUserDetailsService(UserRepository userRepository, UserRolesRepository userRolesRepository) { 
    this.userRepository = userRepository; 
    this.userRolesRepository = userRolesRepository; 
} 


@Override 
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
    User user = userRepository.findByUserName(username); 
    if (null == user) { 
     throw new UsernameNotFoundException("No user present with username: " + username); 
    } else { 
     List<String> userRoles = userRolesRepository.findRoleByUserName(username); 
     return new CustomUserDetails(user, userRoles); 
    } 
} 

} 
,691

이것은 WebSecurity 클래스 내 login.HTML

<!DOCTYPE html> 
 
<html xmlns:th="http://www.thymeleaf.org"> 
 
<head lang="en" xmlns:th="http://www.thymeleaf.org">> 
 
    <title>Spring Framework Guru</title> 
 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
 
</head> 
 
<body class="security-app"> 
 
<div class="details"> 
 
    <h2>Spring Security - App</h2> 
 
</div> 
 

 
<form action="/login" method="post"> 
 

 
    <div class="lc-block"> 
 
     <div> 
 
      <input type="text" class="style-4" name="username" 
 
        placeholder="User Name" /> 
 
     </div> 
 
     <div> 
 
      <input type="password" class="style-4" name="password" 
 
        placeholder="Password" /> 
 
     </div> 
 
     <div> 
 
      <input type="submit" value="Sign In" class="button red small" /> 
 
     </div> 
 
     <th:if test="${param.error ne null}"> 
 
      <div class="alert-danger">Invalid username and password.</div> 
 
     </th:if> 
 
     <th:if test="${param.logout ne null}"> 
 
      <div class="alert-normal">You have been logged out.</div> 
 
     </th:if> 
 
    </div> 
 
    <input type="hidden" name="${_csrf.parameterName}" 
 
      value="${_csrf.token}" /> 
 
</form> 
 

 
</body> 
 
</html>

입니다

2016-10-16 12:15:30.710 WARN 2932 --- [nio-8080-exec-3] o.s.web.servlet.PageNotFound : Request method 'POST' not supported

호출되지 않는 이유가 뭘까요 "구성은 (HttpSecurity HTTP)": 363,210

난 항상 405 오류가 있습니다. 내가 놓친 게 있니?

당신에게 대단히 감사합니다

안드레스

답변

0

시도 또한

.formLogin().loginPage("/xxx").permitAll() 
       .defaultSuccessUrl("/xxx") 
       .failureUrl("/xxx?error") 

추가

컨트롤러 방법과 찾을 수없는 페이지에 대한 스프링 MVC 응용 프로그램에서 하나의 일반적인 이유는 봄의 이상한 매핑 규칙에 따라 현재 URL의 끝에 새 링크 (또는 action = "x"형식)를 추가하여 URL을 작성하십시오. 'Request Method POST Not Supported'는 요청이 POST 요청을 받아들이지 않는 곳을 가리키고 있음을 의미합니다. => URL 매핑이 실패합니다. JSP 사이트에 당신은 항상 그런 다음 귀하의 링크를 잘 URL에서 응용 프로그램 루트 후 설정되어 있는지 확신 할 수 JSTL

<c:url value="/login" var="loginUrl" /> 
<form action="${loginUrl}" method="post"> 

<form action="${pageContext.request.contextPath}/login" method="post"> 

나 같은 URL을 지정해야합니다. 이렇게하면 앞으로 불필요한 많은 문제로부터 당신을 구할 수 있습니다.

+0

@micaro의 빠른 휴식을 가져 주셔서 대단히 감사합니다. 양식을

로 변경했으며 게시물을 찾아서 쿼리합니다. 하지만 이제 내 문제는 게시물의 반환 : "http : // localhost : 8080/login? error"입니다. 사용자 정보를 검색 할 수 없거나 정확하지 않은 것입니까? –

+0

failureUrl은 일반적으로 로그인 페이지와 동일한 페이지입니다. 로그인 오류를 통해 사용자가 잘못된 사용자 이름이나 암호를 입력하면 오류 메시지를보기에 추가 할 수 있습니다. failureUrl은 메시지를 추가하지 않으려는 경우 로그인 할 수 있습니다. – micaro

+1

failureUrl이 끝나면 인증에 문제가 발생합니다. 엄청난 이유가 있습니다. – micaro

관련 문제