最近在做一个spring security的项目,遇到了一个@PreAuthorize 问题。
在interface里面我用@PreAuthorize标记了一些method,
public interface PoiActionInterface {
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String editPoi();
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
public String listPois();
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String generatePoi() throws IOException, TemplateException;
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String deletePoi();
@PreAuthorize("hasRole('ROLE_USER')")
public String trc();
}
在web server启动之后,如果权限不对,会提示exception message: access denied.
但是如果权限对了时候,会出现一些奇怪的问题,
public class POIAction extends ActionSupport implements PoiActionInterface {
private static final long serialVersionUID = "$Id: POIAction.java 42163 2011-08-16 18:39:30Z shany@telenav.com $".hashCode();
@Autowired
private TrcHibernateService trcHibernateService;
@Autowired
private MailService mailService;
@Autowired
private TemplateService templateService;
private UserGeneratedPoi userPoi;
private UserGeneratedPoiDetail userPoiDetail;
private String timeStart;
private String timeEnd;
private Integer action;
private String poiid;
private List<UserGeneratedPoi> userPois;
private static String userFirstName;
public void setUserFirstName(String userFirstName) {
POIAction.userFirstName = userFirstName;
}
public String getUserFirstName() {
return userFirstName;
}
public void setUserPoi(UserGeneratedPoi userPoi) {
this.userPoi = userPoi;
}
public UserGeneratedPoi getUserPoi() {
return userPoi;
}
public String getPoiid() {
return poiid;
}
public void setPoiid(String poiid) {
this.poiid = poiid;
}
public void setTimeStart(String timeStart) {
this.timeStart = timeStart;
}
public String getTimeStart() {
return timeStart;
}
public void setTimeEnd(String timeEnd) {
this.timeEnd = timeEnd;
}
public String getTimeEnd() {
return timeEnd;
}
public void setUserPoiDetail(UserGeneratedPoiDetail userPoiDetail) {
this.userPoiDetail = userPoiDetail;
}
public UserGeneratedPoiDetail getUserPoiDetail() {
return userPoiDetail;
}
public void setAction(Integer action) {
this.action = action;
}
public Integer getAction() {
return action;
}
public void setUserPois(List<UserGeneratedPoi> userPois) {
this.userPois = userPois;
}
public List<UserGeneratedPoi> getUserPois() {
return userPois;
}
public void getFirstName() {
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
POIAction.userFirstName = ((TrcUserDetail) obj).getFirstName();
}
@SkipValidation
@Action(value = "trc", results = { @Result(name = "success", location = "page.addpoi", type = "tiles") })
public String trc() {
return SUCCESS;
}
@SkipValidation
@Action(value = "editpoi", results = { @Result(name = "success", location = "page.editpoi", type = "tiles") })
public String editPoi() {
this.userPoi = trcHibernateService.getById(UserGeneratedPoi.class, Integer.valueOf(poiid));
this.userPoiDetail = trcHibernateService.getById(UserGeneratedPoiDetail.class, Integer.valueOf(poiid));
if (userPoiDetail.getBusinessHour() != null && userPoiDetail.getBusinessHour().split(" ").length > 0) {
setTimeStart(userPoiDetail.getBusinessHour().split(" ")[0]);
setTimeEnd(userPoiDetail.getBusinessHour().split(" ")[1]);
}
return SUCCESS;
}
@SkipValidation
@Action(value = "deletepoi", results = { @Result(name = "success", location = "page.listpois", type = "tiles") })
public String deletePoi() {
this.userPoi = trcHibernateService.getById(UserGeneratedPoi.class, Integer.valueOf(poiid));
this.userPoiDetail = trcHibernateService.getById(UserGeneratedPoiDetail.class, Integer.valueOf(poiid));
trcHibernateService.delete(this.userPoiDetail);
trcHibernateService.delete(this.userPoi);
this.userPois = trcHibernateService.getAll(UserGeneratedPoi.class);
return SUCCESS;
}
@SkipValidation
@Action(value = "listpois", results = { @Result(name = "success", location = "page.listpois", type = "tiles") })
public String listPois() {
getFirstName();
this.userPois = trcHibernateService.getAll(UserGeneratedPoi.class);
return SUCCESS;
}
@Validations(requiredStrings = {
@RequiredStringValidator(type = ValidatorType.FIELD, fieldName = "userPoi.brandName", message = "You must enter a brand name for POIs."),
@RequiredStringValidator(type = ValidatorType.FIELD, fieldName = "userPoi.street1", message = "You must enter a street address for POIs."),
@RequiredStringValidator(type = ValidatorType.FIELD, fieldName = "userPoi.city", message = "You must enter a city name for POIs."),
@RequiredStringValidator(type = ValidatorType.FIELD, fieldName = "userPoi.state", message = "You must enter a state name for POIs."),
@RequiredStringValidator(type = ValidatorType.FIELD, fieldName = "userPoi.zip", message = "You must enter a zip code for POIs.") }, stringLengthFields = { @StringLengthFieldValidator(type = ValidatorType.FIELD, trim = true, minLength = "1", maxLength = "20", fieldName = "userPoi.street1", message = "Street 1 only can have at most 20 characters") })
@Action(value = "generatepoi", results = { @Result(name = "success", location = "page.message", type = "tiles"),
@Result(name = "input", location = "page.addpoi", type = "tiles") })
public String generatePoi() throws IOException, TemplateException {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
User user = new User();
user.setName(authentication.getName());
user = trcHibernateService.getAll(User.class, user).get(0);
userPoi.setUserByUserId(user);
if (userPoi.getId() == null) {
trcHibernateService.save(userPoi);
} else {
try {
trcHibernateService.merge(userPoi);
setAction(Integer.valueOf(1));
} catch (DataIntegrityViolationException dve) {
addFieldError("userPoi.id", getText("dupicate poi id"));
return INPUT;
}
}
userPoiDetail.setId(userPoi.getId());
userPoiDetail.setBusinessHour(getTimeStart() + " " + getTimeEnd() + " ");
if (trcHibernateService.getById(UserGeneratedPoiDetail.class, userPoi.getId()) == null) {
userPoiDetail.setUserGeneratedPoi(userPoi);
trcHibernateService.save(userPoiDetail);
} else {
try {
trcHibernateService.merge(userPoiDetail);
} catch (DataIntegrityViolationException dve) {
addFieldError("userPoiDetail.poiId", getText("dupicate poi detail id"));
return INPUT;
}
}
if (action == null) {
addActionMessage(getText("addpoi.successful", null, ""));
mailService.sendMail("shany@telenav.com", "POI Added", templateService.getNewPoiNotificationText(userPoi.getId().toString()));
} else {
addActionMessage(getText("editpoi.successful", null, ""));
}
return SUCCESS;
}
}
所有@autowired的object全部都是null, 所以在做action的时候会有Nullpointexception出现。
Exception Stack:
java.lang.NullPointerException at com.telenav.trc.action.common.POIAction.listPois(POIAction.java:172) at com.telenav.trc.action.common.POIActionFastClassByCGLIB83c14b0a.invoke() at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:67) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621) at com.telenav.trc.action.common.POIActionEnhancerByCGLIB40826733.listPois() at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:61) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:270) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:498) at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:109) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:662)