[SPRING] Spring Security는 로그인 후 항상 403 accessDeniedPage를 반환합니다 [duplicate]
SPRINGSpring Security는 로그인 후 항상 403 accessDeniedPage를 반환합니다 [duplicate]
저는 Spring을 처음 사용하고 있으며 Spring 보안을 사용하여 간단한 로그인 페이지를 구현하려고했습니다. 하지만 항상 로그인 자격 증명을 제공 한 후 거부 된 URL에 액세스합니다. loadUserByUsername () 메서드는 올바른 사용자 이름과 암호를 제공 한 후에 항상 사용자를 반환합니다. 하지만 그 사용자 개체가 반환 된 후에 어떤 일이 발생하는지 찾는 방법을 모르겠습니다.
사용자에게는 하나의 역할 만 있습니다. 이 메소드는 SUPER_USER 역할을 가진 사용자를 리턴합니다.
여기 내 봄 보안 구성 클래스입니다
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = AppConfig.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("Inside configureGlobalSecurity method");
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("Inside configure method");
http.authorizeRequests().antMatchers("/", "/list")
.access("hasRole('SUPER_USER') or hasRole('NORMAL_USER') or hasRole('CUSTOMER')")
.and().formLogin().loginPage("/login")
.loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password").and()
.csrf().and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
System.out.println("Inside authenticationProvider method");
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Bean
public AuthenticationTrustResolver getAuthenticationTrustResolver() {
return new AuthenticationTrustResolverImpl();
}
}
이것은 내 UserDetailsServiceImpl 클래스입니다.
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.user.UserDao;
import com.entity.user.User;
@Service("userDetailsService")
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UserDao userDao = null;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.getUserByUsername(username);
if(user!=null) {
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority(user.getRole().getDescription().getStringVal()));
org.springframework.security.core.userdetails.User u = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, true, true, true,grantedAuthorities);
return u;
} else {
throw new UsernameNotFoundException("User Does not Exist");
}
}
}
이 메서드는 올바른 사용자 이름과 암호를 제공 한 후에 항상 사용자를 반환합니다. 이것은 반환하는 것입니다.
org.springframework.security.core.userdetails.User@a3b: Username: RM; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: SUPER_USER
이것은 Controller 클래스입니다.
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/")
public class LoginController {
@Autowired
AuthenticationTrustResolver authenticationTrustResolver;
@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {
System.out.println("Inside controller list");
return "first";
}
@RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
@ResponseBody
public String accessDeniedPage(ModelMap model) {
return "Access Dennied";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage() {
System.out.println("Inside controller login");
if (isCurrentAuthenticationAnonymous()) {
return "login";
} else {
return "redirect:/list";
}
}
@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
SecurityContextHolder.getContext().setAuthentication(null);
}
return "redirect:/login?logout";
}
/**
* This method returns true if users is already authenticated [logged-in], else false.
*/
private boolean isCurrentAuthenticationAnonymous() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authenticationTrustResolver.isAnonymous(authentication);
}
내 로그인 양식입니다.
<form id="login" name="login" class="form-signin" action="/SpringView/login" method=POST>
<span id="reauth-email" class="reauth-email"></span>
<input type="text" id="username" name="username" class="form-control" placeholder="Email address" required
autofocus>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
<div id="remember" class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<button class="btn btn-lg btn-block btn-signin " type="submit">Sign in</button>
</form><!-- /form -->
해결법
-
==============================
1.Userme, 어떻게 Security의 UserDetails 객체에 역할 이름을 짓고 있습니까?
Userme, 어떻게 Security의 UserDetails 객체에 역할 이름을 짓고 있습니까?
스프링 시큐리티의 아키텍처 결정에 따라 당신에게 권한 'ROLE_'을 추가해야합니다.
new SimpleGrantedAuthority("ROLE_" + roleName);
에
from https://stackoverflow.com/questions/42180028/spring-security-always-return-the-403-accessdeniedpage-after-login by cc-by-sa and MIT license
'SPRING' 카테고리의 다른 글
[SPRING] Keycloak 스프링 보안 클라이언트 자격 증명 부여 (0) | 2019.02.26 |
---|---|
[SPRING] GAE에서 작동하지 않는 Spring Autowiring (0) | 2019.02.26 |
[SPRING] Eclipse에서 모든 JUnit 테스트를 독립적으로 실행하고 매번 Spring 컨텍스트를 다시로드합니다. (0) | 2019.02.26 |
[SPRING] 봄 mvc 모든 요청으로 만든 새 콩 개체가 있나요? (0) | 2019.02.26 |
[SPRING] 부모 태그에서 Maven 속성을 확인할 수 없음 (0) | 2019.02.26 |