我有一个使用JSF的Web应用程序,Spring安全性用于登录和授权。
当用户在特定页面中键入而他未登录时,例如 localhost:8080/APP/page.xhtml
,应用程序重定向到登录页面,这是可以的。之后,用户登录,但他被重定向到的页面index.xhtml
这是默认的欢迎页面,而不是page.xhtml
。
我想要以下行为:用户转到localhost:8080/APP/page.xhtml
,他被重定向以登录,之后他应该被重定向到他想要的页面 - page.xhtml
。
已编辑 - 弹簧安全.xml片段:
<security:http auto-config="true">
<security:intercept-url pattern="/javax.faces.resource/*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<security:intercept-url pattern="/login.xhtml" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<security:intercept-url pattern="/**" access="ROLE_UNALLOCATED, ROLE_MANAGER"/>
<security:intercept-url pattern="/pages/management/" access="ROLE_MANAGER"/>
<security:intercept-url pattern="/pages/requests/" access="ROLE_UNALLOCATED, ROLE_EMPLOYEE, ROLE_TEAM_LEADER, ROLE_MANAGER"/>
<security:form-login login-page="/login.xhtml"
/>
<security:logout logout-url="/j_spring_security_logout"
logout-success-url="/login.xhtml"
invalidate-session="true"/>
</security:http>
有什么想法吗?谢谢
编辑:
我以为是因为:
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>/index.xhtml</welcome-file>
</welcome-file-list>
来自网络.xml。我删除了它,但结果相同。
后期编辑:
我刚刚注意到我的自定义登录控制器中有一行if (authenticationResponseToken.isAuthenticated())
这几乎可以肯定是问题的根源:
登录控制器:
@ManagedBean(name = "loginController")
@SessionScoped
@Controller
public class LoginController implements Serializable {
private static final long serialVersionUID = 1L;
@Autowired
IUserService userService;
@Autowired
@Qualifier("authenticationManager")
protected AuthenticationManager authenticationManager;
// save the current user after login to be able to inject it in other places
// as needed
private User currentUser;
/**
* This action logs the user in and returns to the secure area.
*
* @return String path to secure area
*/
public String loginUsingSpringAuthenticationManager() {
// get backing bean for simple redirect form
LoginFormBackingBean loginFormBean = (LoginFormBackingBean) FacesUtils
.getBackingBean("loginFormBean");
// simple token holder
Authentication authenticationRequestToken = createAuthenticationToken(loginFormBean);
// authentication action
try {
Authentication authenticationResponseToken = authenticationManager
.authenticate(authenticationRequestToken);
Authentication authCopy = null;
final Object principal = authenticationResponseToken.getPrincipal();
if (principal instanceof LdapUserDetailsImpl) {
LdapUserDetailsImpl userImpl = (LdapUserDetailsImpl) principal;
userImpl.getUsername();
// here check if we already have a User with his DN in the DB
// get the User by DN
User u = userService.getUserByDn(userImpl.getDn());
// if a user with this DN does not exist in the DB, create a new
// one with the DN from LDAP and the default settings for a new
// user
if (null == u) {
u = userService.createNewUserFromDn(userImpl.getDn(),
userImpl.getUsername());
}
// set the obtained user as the current user
setCurrentUser(u);
List<GrantedAuthority> grAuth = new ArrayList<GrantedAuthority>();
// after this, do the role authority stuff
// here loop through user roles if he has more and
if (null != u.getUserTeamRoles()) {
for (UserTeamRole urt : u.getUserTeamRoles()) {
// here get role for every UserTeamRole
grAuth.add(new SimpleGrantedAuthority(urt.getRole()
.getName()));
}
}
// add the above found roles to the granted authorities of the
// current authentication
authCopy = new UsernamePasswordAuthenticationToken(
authenticationResponseToken.getPrincipal(),
authenticationResponseToken.getCredentials(), grAuth);
}
SecurityContextHolder.getContext().setAuthentication(authCopy);
// ok, test if authenticated, if yes reroute
if (authenticationResponseToken.isAuthenticated()) {
// lookup authentication success url, or find redirect parameter
// from login bean
return "index.xhtml?faces-redirect=true";
}
} catch (BadCredentialsException badCredentialsException) {
// FacesMessage facesMessage = new FacesMessage(
// "Login Failed: please check your username/password and try again.");
// FacesContext.getCurrentInstance().addMessage(null, facesMessage);
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Sample error message",
"Login Failed! Please check your credentials"));
} catch (LockedException lockedException) {
FacesMessage facesMessage = new FacesMessage(
"Account Locked: please contact your administrator.");
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
} catch (DisabledException disabledException) {
FacesMessage facesMessage = new FacesMessage(
"Account Disabled: please contact your administrator.");
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
}
return null;
}
private Authentication createAuthenticationToken(
LoginFormBackingBean loginFormBean) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
loginFormBean.getUserName(), loginFormBean.getPassword());
return usernamePasswordAuthenticationToken;
}
如何重定向到我需要的页面?我有一个包含用户和密码的登录Bean,我可以添加一个重定向URL,但是如何找到以前的URL路径?
Spring Security 通过使用 SavedRequestAwareAuthenticationSuccessHandler(在幕后使用 HttpSessionRequestCache)在 AbstractAuthenticationProcessingFilter 中为您实现此逻辑(通常使用 UsernamePasswordAuthenticationFilter 的具体实现)。由于您已经编写了一个控制器来进行身份验证(而不是使用内置支持),因此您需要自己实现此逻辑。与其自己实现所有逻辑,不如重用与 Spring Security 相同的类。
例如,您的登录控制器可能会更新如下:
public class LoginController implements Serializable {
// ... same as before ...
private RequestCache requestCache = new HttpSessionRequestCache();
public String loginUsingSpringAuthenticationManager() {
// ... just as you had been doing ...
if (authenticationResponseToken.isAuthenticated()) {
HttpServletRequest request = (HttpServletRequest)
FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse)
FacesContext.getCurrentInstance().getExternalContext().getResponse();
SavedRequest savedRequest = requestCache.getRequest(request, response);
return savedRequest.getRedirectUrl();
}
// ... same as you had ...
}
}
如果未定义default-target-url
Spring Security 会尝试重定向到以前的 url,因此您只需从form-login
标签中删除default-target-url
属性。
<security:form-login login-page="/login.xhtml" />
更新
如果您的筛选器链中包含ExceptionTranslationFilter
,则它应该缓存 HTTP 请求。因此,在您的自定义登录控制器中,您可以尝试从此缓存请求中获取重定向 URL。
RequestCache requestCache = new HttpSessionRequestCache();
SavedRequest savedRequest = requestCache.getRequest(request, response);
String targetUrl = savedRequest.getRedirectUrl();
要向控制器注入请求,请尝试:
private @Autowired HttpServletRequest request;
或
HttpServletRequest curRequest = ((ServletRequestAttributes)
RequestContextHolder.currentRequestAttributes()) .getRequest();
更改
<security:form-login login-page="/login.xhtml"
default-target-url="/index.xhtml" />
自
<security:form-login login-page="/login.xhtml"
default-target-url="/page.xhtml" />
要获得您所描述的行为,您应该在 Web 中添加一个 spring 安全过滤器.xml如下所示:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
也许你还必须编辑你的春天安全.xml。有关更多信息,请参阅此链接: Spring Security with DedelegateatingFilterProxy
检查此讨论,它看起来与您的问题相似,可能会对您有所帮助: http://forum.springsource.org/showthread.php?128480-重定向到原始-(未经身份验证的页面)-弹簧后-安全性-openid-authentic