如何在安卓中使用JWT?

huangapple go评论75阅读模式
英文:

how should i use JWT in android?

问题

我想使用jjwt来创建登录活动。
所以我不知道如何使用它。我在<https://github.com/jwtk/jjwt>上阅读了它,但由于我的英语不流利,所以我无法理解。我希望你能给我一个示例来帮助我理解。我应该向服务发送任何内容吗?还是我只需要在我的DatabaseHelper中使用sqlite openhelper保存密钥。
我使用OkHttp将用户名和密码发送到服务并使用json进行获取。
这是我的活动:

MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
    public void btnSignin_Clicked(View view){
        String username=((EditText)findViewById(R.id.txtUsername)).getText().toString();
        String password=((EditText)findViewById(R.id.txtPassword)).getText().toString();
        new SigninTask().execute(username,password);
    }
    public void btnSignup_Clicked(View view){
        ((EditText)findViewById(R.id.txtUsername)).setText("");
        ((EditText)findViewById(R.id.txtPassword)).setText("");
        String username=((EditText)findViewById(R.id.txtUsername)).getText().toString();
        String password=((EditText)findViewById(R.id.txtPassword)).getText().toString();
        new SignupTask().execute(username,password);
    }

    private class SignupTask extends AsyncTask<String,Object,String>{
        @Override
        protected String doInBackground(String... strings) {

            try {
                return
                new OkHttpClient()
                        .newCall(
                                new Request.Builder()
                                .url("http://localhost:8080/Service/signup?username="+strings[0]+"&amp;password="+strings[1])
                                .build()
                        )
                        .execute()
                        .body()
                        .string();
            }catch (Exception e){
                return null;
            }

        }

        @Override
        protected void onPostExecute(String s) {
            SimpleDialog dialog=new SimpleDialog();
            dialog.setContext(MainActivity.this);
            dialog.setTitle("Error");
          try {
              JSONObject jsonObject=new JSONObject(s);
              Boolean result=jsonObject.getBoolean("value");
              if (result){
                  String username= ((EditText)findViewById(R.id.txtUsername)).getText().toString();
                  dialog.setMessage("Signup completed)");
                  ((EditText)findViewById(R.id.txtUsername)).setText("");
                  ((EditText)findViewById(R.id.txtPassword)).setText("");

              }else {
                  ((EditText)findViewById(R.id.txtUsername)).setText("");
                  ((EditText)findViewById(R.id.txtPassword)).setText("");
                  dialog.setMessage("Sign up failed !");
              }
          }catch (Exception e){
              dialog.setMessage("Error occured !");
          }
          dialog.show(getSupportFragmentManager(),"dialog");
        }
    }

    private class SigninTask extends AsyncTask<String,Object,String>{
        @Override
        protected String doInBackground(String... strings) {
            try {
              return   new OkHttpClient()
                        .newCall(
                                new Request.Builder()
                                        .url("http://localhost:8080/Service/authorize?username="+strings[0]+"&amp;password="+strings[1])
                                        .build()
                        )
                        .execute()
                        .body()
                        .string();
            }catch (Exception e){
                return null;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            SimpleDialog dialog=new SimpleDialog();
            dialog.setContext(MainActivity.this);
            dialog.setTitle("Error");
            try {
                JSONObject jsonObject=new JSONObject(s);
                Boolean result=jsonObject.getBoolean("value");
                if (result){
                    String username=((EditText)findViewById(R.id.txtUsername)).getText().toString();
                    String password=((EditText)findViewById(R.id.txtPassword)).getText().toString();
                    Intent intent=new Intent(MainActivity.this,CategoryActivity.class);
                    User user=new User();
                    user.setUsername(username);
                    user.setPassword(password);

                    intent.putExtra("user",user);
                    startActivity(intent);
                    finish();
                }else {
                    dialog.setMessage("Invalid username or password !");
                }
            }catch (Exception e){
                dialog.setMessage("Error occured !");
            }
            dialog.show(getSupportFragmentManager(),"dialog");
        }
    }
}
英文:

I want to use jjwt to create a login activity.
so i don't know how to use it . i read it in <https://github.com/jwtk/jjwt> but i couldn't understand because my English is not fluent. i want you to give me an example to understand it. should i send anything to service ? or just i should save key in my DatabaseHelper with sqlite openhelper .
i use OkHttp for sending username and password to service and get it with json.
this is my activity :

MainActivity :

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnSignin_Clicked(View view){
String username=((EditText)findViewById(R.id.txtUsername)).getText().toString();
String password=((EditText)findViewById(R.id.txtPassword)).getText().toString();
new SigninTask().execute(username,password);
}
public void btnSignup_Clicked(View view){
((EditText)findViewById(R.id.txtUsername)).setText(&quot;&quot;);
((EditText)findViewById(R.id.txtPassword)).setText(&quot;&quot;);
String username=((EditText)findViewById(R.id.txtUsername)).getText().toString();
String password=((EditText)findViewById(R.id.txtPassword)).getText().toString();
new SignupTask().execute(username,password);
}
private class SignupTask extends AsyncTask&lt;String,Object,String&gt;{
@Override
protected String doInBackground(String... strings) {
try {
return
new OkHttpClient()
.newCall(
new Request.Builder()
.url(&quot;http://localhost:8080/Service/signup?username=&quot;+strings[0]+&quot;&amp;password=&quot;+strings[1])
.build()
)
.execute()
.body()
.string();
}catch (Exception e){
return null;
}
}
@Override
protected void onPostExecute(String s) {
SimpleDialog dialog=new SimpleDialog();
dialog.setContext(MainActivity.this);
dialog.setTitle(&quot;Error&quot;);
try {
JSONObject jsonObject=new JSONObject(s);
Boolean result=jsonObject.getBoolean(&quot;value&quot;);
if (result){
String username= ((EditText)findViewById(R.id.txtUsername)).getText().toString();
dialog.setMessage(&quot;Signup completed)&quot;);
((EditText)findViewById(R.id.txtUsername)).setText(&quot;&quot;);
((EditText)findViewById(R.id.txtPassword)).setText(&quot;&quot;);
}else {
((EditText)findViewById(R.id.txtUsername)).setText(&quot;&quot;);
((EditText)findViewById(R.id.txtPassword)).setText(&quot;&quot;);
dialog.setMessage(&quot;Sign up failed !&quot;);
}
}catch (Exception e){
dialog.setMessage(&quot;Error occured !&quot;);
}
dialog.show(getSupportFragmentManager(),&quot;dialog&quot;);
}
}
private class SigninTask extends AsyncTask&lt;String,Object,String&gt;{
@Override
protected String doInBackground(String... strings) {
try {
return   new OkHttpClient()
.newCall(
new Request.Builder()
.url(&quot;http://localhost:8080/Service/authorize?username=&quot;+strings[0]+&quot;&amp;password=&quot;+strings[1])
.build()
)
.execute()
.body()
.string();
}catch (Exception e){
return null;
}
}
@Override
protected void onPostExecute(String s) {
SimpleDialog dialog=new SimpleDialog();
dialog.setContext(MainActivity.this);
dialog.setTitle(&quot;Error&quot;);
try {
JSONObject jsonObject=new JSONObject(s);
Boolean result=jsonObject.getBoolean(&quot;value&quot;);
if (result){
String username=((EditText)findViewById(R.id.txtUsername)).getText().toString();
String password=((EditText)findViewById(R.id.txtPassword)).getText().toString();
Intent intent=new Intent(MainActivity.this,CategoryActivity.class);
User user=new User();
user.setUsername(username);
user.setPassword(password);
intent.putExtra(&quot;user&quot;,user);
startActivity(intent);
finish();
}else {
dialog.setMessage(&quot;Invalid username or password !&quot;);
}
}catch (Exception e){
dialog.setMessage(&quot;Error occured !&quot;);
}
dialog.show(getSupportFragmentManager(),&quot;dialog&quot;);
}
}
}

答案1

得分: 0

通常情况下,您会将登录数据(用户名、密码)发送到对您进行身份验证的服务器,然后该服务器会发送回一个JWT令牌。您可以将此令牌存储在您的应用程序中,然后在每个向服务器发送的请求中携带此令牌,以进行身份验证。

英文:

Normally you send your login data (user name, password) to the server that authenticates you, and this server sends back a JWT. You can store this token in your application. And then y' send this token within every request to the serve to authenticate you.

huangapple
  • 本文由 发表于 2020年4月9日 17:20:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/61117822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定