我已閱讀關於spring security的一些示例,但我無法使其工作......我不確定是否缺少某些東西。請我欣賞一些說明,因爲我很難理解這一點。Spring Security java配置和登錄表單
使用Spring mvc 4.3.3,Spring Security 4.2.0,Tiles 3,CSS,Java 1.7,Eclipse neon。
1.-我的第一頁是登錄頁面(我沒有使用主頁或索引)。
2.-我希望Spring Security能夠接受用戶並從我的登錄名(瀏覽器中顯示的第一頁)傳遞,同時我在登錄時使用了<form action="<c:url value='j_spring_security_check' />" method="post">
,但出現了一些問題。
3 .-我希望它重定向到同一視圖的所有用戶/ myPanel(我會改變菜單acording用戶角色)
結構;
類(除去進口和包); UPDATE:
ApplicationContextConfig.java
@Configuration
@ComponentScan("mx.com.myapp.*")
@Import({ SecurityConfig.class })
public class ApplicationContextConfig {
@Bean(name = "viewResolver")
public ViewResolver getViewResolver() {
UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
// TilesView 3
viewResolver.setViewClass(TilesView.class);
return viewResolver;
}
@Bean(name = "tilesConfigurer")
public TilesConfigurer getTilesConfigurer() {
TilesConfigurer tilesConfigurer = new TilesConfigurer();
// TilesView 3
tilesConfigurer.setDefinitions("/WEB-INF/tiles.xml");
return tilesConfigurer;
}
WebMvcConfig.java:
@Configuration
//@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
//
// // Default..
// }
//
// @Override
// public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
// configurer.enable();
// }
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}
SpringWebAppInitializer.java
public class SpringWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(ApplicationContextConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("SpringDispatcher",
new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
// UtF8 Charactor Filter.
FilterRegistration.Dynamic fr = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
fr.setInitParameter("encoding", "UTF-8");
fr.setInitParameter("forceEncoding", "true");
fr.addMappingForUrlPatterns(null, true, "/*");
}
}
SpringSecurityInitializer.java
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("mkyong").password("123456").roles("ADMIN");
System.out.println("SpringSecurity ConfigureGlobal");
}
// .csrf() is optional, enabled by default, if using WebSecurityConfigurerAdapter constructor
// @Override
// protected void configure(HttpSecurity http) throws Exception {
//
// System.out.println("SpringSecurity configure");
// http.authorizeRequests()
// .antMatchers("/").permitAll()
// .antMatchers("/myPanel**").access("hasRole('ADMIN')")
// .and().formLogin()
// .usernameParameter("username").passwordParameter("password")
// .permitAll()
// .and()
// .csrf();
// }
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated().and().formLogin()
.loginPage("/login").failureUrl("/login?error").permitAll().and()
.logout().permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/path/**");
}
}
MyController.java
@Controller
public class MyController {
@RequestMapping(value = { "/" })
public String loginPage(Model model) {
return "loginPage";
}
@RequestMapping(value = { "/myPanel" }, method = RequestMethod.POST)
public ModelAndView myPanel(HttpServletRequest request, HttpServletResponse response) {
System.out.println("INICIA REQUEST");
System.out.println("-------- " + request.getParameter("user"));
String message = "<br><div style='text-align:center;'>"
+ "<h3>********** This is protected page!</h3> **********</div><br><br>";
System.out.println("TERMINA REQUEST");
return new ModelAndView("homePage", "message", message);
}
//Spring Security see this :
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView login(
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
System.out.println("/login SpringSecurity");
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("homePage");
return model;
}
}
的login.jsp
<form action="<c:url value='/login' />" method="post">
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<input type="text" name="username" placeholder="Username" required="required" class="input-txt" />
<input type="password" name="password" placeholder="Password" required="required" class="input-txt" />
<div class="login-footer">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<strong><a href="#" class="lnk">I've forgotten something</a> |
<a href="#" class="lnk">Register</a></strong>
<button type="submit" class="btn btn--right">Sign in</button>
</div>
</form>
提前非常感謝。
我懷疑你需要formlogin指向/登錄,但在彈簧安全性上進行漸變記錄,它會告訴你它在哪裏正在尋找login.html。 – farrellmr
但是,如果我這樣做,它會重新發送我的登錄權限?畢竟我的登錄是我的第一頁。 :困惑: – Dr3ko