通过角度和密码编码调用手动Spring安全实现

时间:2017-01-11 10:06:28

标签: java spring authentication spring-security thymeleaf

我很抱歉我的英语不好......

我正在使用Spring启动,Spring Security模块和Angular。我也有一个自定义数据库。

我改变了所有项目架构。在此之前,我通过登录表单在我的HTML中调用了thymeleaf: th:action =" @ / login" 。现在,我删除了百里香,所以我用AngularJS实现了一个简单的表格。

我想做的是:

  • 点击我的HTML页面中的按钮确定
  • 调用角度函数确定
  • 使用用户名和密码作为参数确定
  • 执行POST请求
  • 使用@RequestMapping调用Java控制器(value =" / login" method = RequestMethod.POST)注释确定
  • 调用 SecurityConfig.java 中的configAuthentication()。

之前,当我使用百里香时,通过拦截请求自动调用此函数。但现在我需要手动调用它。我怎么能这样做?

我在这里发布了我的部分代码:

我的login.html中的

表单

<form autocomplete="off">
     <label>{{'login.username' | translate}}</label>
     <input class="form-control" type="text" name="username" ng-change="message = false" ng-model="username" required/>
      <label>{{'login.password' | translate}}</label>
      <input class="form-control" type="password" name="password" ng-change="message = false" ng-model="password" required/>
      <button type="submit" class="btn btn-default" ng-click="login()">{{'login.button' | translate}}</button>
 </form>



我在login.js中的角度函数

$scope.login = function(){
        var dataToSend = {
            username : $scope.username,
            password : $scope.password
        }
        $http.post('/login', dataToSend).success(function(){
            alert("ok");
        }).error(function () {
            alert("skdjs");
        })
    }



我的UserController.java中的java方法(我需要用你的命题实现这个方法)

@RequestMapping(value="/login", method = RequestMethod.POST)
public JSONObject login(HttpServletRequest request, HttpServletResponse response, @RequestBody User user) {

}

我可以轻松获得密码和用户名,但我没有方法getAuthorities。 我有一个加密的密码,你可以在我的 SecurityConfig.java

中看到


有关退出的信息,我有这个并且有效

@RequestMapping(value="/user/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }
    return "redirect:/login?logout";
}



最后,我的文件 SecurityConfig.java ,我的方法 configAuthentication 未被调用。

package betizy.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


@Autowired
DataSource dataSource;

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    System.out.println("djfkdjfdkfjkd");

    auth.jdbcAuthentication().dataSource(dataSource)
            .passwordEncoder(passwordEncoder())
            .usersByUsernameQuery(
                    "select use_username, use_password, use_enabled from use_user where use_username=?")
            .authoritiesByUsernameQuery(
                    "select use_username, usr_role from usr_user_role, use_user where use_id = usr_use_id and use_username=?");
}

@Bean
public PasswordEncoder passwordEncoder(){
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    return encoder;
}


@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            //.antMatchers("/hello").access("hasRole('ROLE_ADMIN')")
            .antMatchers(   "/",
                            "/**",
                            "/user/activate",
                            "/user/activate/**",
                            "/user/create",
                            "/user/register",
                            "/webjars/**",
                            "/templates/**",
                            "/static/**",
                            "/favicon.ico"
            ).permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().loginPage("/login").permitAll()
            .usernameParameter("username").passwordParameter("password")
            .and()
            .logout().permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/403")
            .and()
            .csrf().disable();
}
}


非常感谢你的帮助!

PS:我读过Spring security ang Angular教程,但我想使用我前面描述的方法

修改

我正在使用Spring启动,而我的application.properties是:

spring.datasource.url = jdbc:mysql://localhost/betizy
spring.datasource.username =  root
spring.datasource.password =
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

这就是我的Spring Security配置

1 个答案:

答案 0 :(得分:0)

您可以使用org.springframework.security.authentication.AuthenticationManager

@Autowired
private AuthenticationManager authenticationManager;

@RequestMapping(value="/login", method = RequestMethod.POST)
public JSONObject login(HttpServletRequest request, HttpServletResponse response, @RequestBody User user) {

    //does the authentication
    final Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                    user.getUsername(),
                    user.getPassword()
            )
    );
    SecurityContextHolder.getContext().setAuthentication(authentication);

    //just an example of return - you could easily just return the 200 code or smth
    return Json.createObjectBuilder()
            .add("firstName", user.getFirstName())
            .add("lastName", user.getLastName())
            .add("status", HttpStatus.OK);
}

希望它有所帮助。