Java 手动Spring安全实现,使用angular和密码编码的调用

Java 手动Spring安全实现,使用angular和密码编码的调用,java,spring,authentication,spring-security,thymeleaf,Java,Spring,Authentication,Spring Security,Thymeleaf,我事先为我的英语不好感到抱歉 我正在使用Spring boot、Spring安全模块和Angular。我也有一个自定义数据库 我改变了我所有的项目架构。之前,我在HTML中使用登录表单调用了thymeleaf:th:action=“@/login”。现在,我删除了thymeleaf,所以我用AngularJS实现了一个简单的表单 我想做的是: 单击我的HTML页面中的按钮OK 调用角度函数OK 使用用户名和密码作为参数执行POST请求OK 使用@RequestMapping(value=“/l

我事先为我的英语不好感到抱歉

我正在使用Spring boot、Spring安全模块和Angular。我也有一个自定义数据库

我改变了我所有的项目架构。之前,我在HTML中使用登录表单调用了thymeleaf:th:action=“@/login”。现在,我删除了thymeleaf,所以我用AngularJS实现了一个简单的表单

我想做的是:

  • 单击我的HTML页面中的按钮OK
  • 调用角度函数OK
  • 使用用户名和密码作为参数执行POST请求OK
  • 使用@RequestMapping(value=“/login”method=RequestMethod.POST)注释调用Java控制器OK
  • 调用SecurityConfig.java中的我的configAuthentication()
以前,当我使用thymeleaf时,这个函数是通过截取请求自动调用的。但现在我需要手动调用它。我该怎么做

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

我的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>


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

我可以轻松地拥有密码和用户名,但我没有权限。 我有一个加密密码,您可以在我的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安全指南,但我想使用前面介绍的方法

编辑

我正在使用Spring boot,我的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安全配置的全部内容

您可以使用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);
}

希望有帮助。

可能重复我不明白为什么?我的问题是,我需要一种方法来链接我的UserController.java和SecurityConfig.java中的方法@邮戳是一种解决方案吗?我认为不是,这就是我认为它不是复制品的原因。此外,我不太理解他在相关主题中的问题。
spring.datasource.url = jdbc:mysql://localhost/betizy
spring.datasource.username =  root
spring.datasource.password =
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
@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);
}