Spring Security java配置和登录表单
我读过关于spring security的文章,也看到了一些例子,但我无法让它工作。。。我不确定我是否遗漏了什么。请允许我解释一下,因为我很难理解这一点 使用SpringMVC4.3.3、SpringSecurity 4.2.0、Tiles 3、CSS、Java1.7和EclipseNeon 1.-我的第一页是登录页,我不使用主页或索引 2.-我希望Spring Security从浏览器中显示的我的登录第一页获取用户并通过,我也在登录中使用,但出现了一些问题 3.-我希望它重定向到所有用户的相同视图/myPanel我将根据用户角色更改菜单 结构 进口和包装;更新: ApplicationContextConfig.javaSpring Security java配置和登录表单,java,spring-mvc,spring-security,apache-tiles,Java,Spring Mvc,Spring Security,Apache Tiles,我读过关于spring security的文章,也看到了一些例子,但我无法让它工作。。。我不确定我是否遗漏了什么。请允许我解释一下,因为我很难理解这一点 使用SpringMVC4.3.3、SpringSecurity 4.2.0、Tiles 3、CSS、Java1.7和EclipseNeon 1.-我的第一页是登录页,我不使用主页或索引 2.-我希望Spring Security从浏览器中显示的我的登录第一页获取用户并通过,我也在登录中使用,但出现了一些问题 3.-我希望它重定向到所有用户的相同
@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;
}
@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/**");
}
}
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, "/*");
}
}
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
SpringSecurityInitializer.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, "/*");
}
}
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
SecurityConfig.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;
}
@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>
非常感谢。您丢失的许可证都在登录页面上-
@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();
}
看来你的设置太复杂了,试着简化一下 Spring安全配置:
@Configuration
public static class WebFormSecurity extends WebSecurityConfigurerAdapter {
@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/**");
}
和MVC配置,您不必实现/login操作:
我怀疑您需要formlogin来指向/login,但是在spring security上快速登录,它会告诉您它在哪里查找login.html。但是如果我这样做,它会将我重新发送到登录,对吗?毕竟,我的登录是我的第一页:惑儒:嘿,法雷尔,仍然得到404:SFO。有一刻我认为它有效,但没有。。。哦,我的科科罗。。。我的jsp可能有问题吗?